///|
/// # 表格图像提取 ocr/table_image_extraction
///
/// 图像处理库子模块
/// 图像处理库子模块 Image processing library submodule
// 表格识别增强与图片提取(v12.20.0)
// 真正的表格线检测、单元格分割、表格结构分析、图片区域裁剪保存

///|
/// 表格线检测结果
#derive(Eq, @debug.Debug)
pub(all) struct TableDetectionResult {
  horizontal_lines : Array[(Int32, Int32, Int32)] // (y, x_start, x_end)
  vertical_lines : Array[(Int32, Int32, Int32)] // (x, y_start, y_end)
  intersections : Array[(Int32, Int32)] // (x, y) 交叉点
  num_rows : Int32
  num_cols : Int32
  confidence : Double
}

///|
pub extend TableDetectionResult with Eq::{not_equal, equal}

///|
pub extend TableDetectionResult with @debug.Debug::{to_repr}

///|
/// 单元格内容
#derive(Eq, @debug.Debug)
pub(all) struct TableCellContent {
  row : Int32
  col : Int32
  row_span : Int32
  col_span : Int32
  x : Int32
  y : Int32
  width : Int32
  height : Int32
  text : String
  is_header : Bool
  is_merged : Bool
}

///|
pub extend TableCellContent with Eq::{not_equal, equal}

///|
pub extend TableCellContent with @debug.Debug::{to_repr}

///|
/// 完整表格识别结果
#derive(Eq, @debug.Debug)
pub(all) struct EnhancedTableResult {
  x : Int32
  y : Int32
  width : Int32
  height : Int32
  rows : Int32
  cols : Int32
  cells : Array[TableCellContent]
  has_header : Bool
  header_rows : Int32
  detection : TableDetectionResult
  confidence : Double
}

///|
pub extend EnhancedTableResult with Eq::{not_equal, equal}

///|
pub extend EnhancedTableResult with @debug.Debug::{to_repr}

///|
/// 提取的图片区域
#derive(Eq, @debug.Debug)
pub(all) struct ExtractedImage {
  x : Int32
  y : Int32
  width : Int32
  height : Int32
  image_type : String // "photo" / "diagram" / "chart" / "logo" / "signature"
  confidence : Double
  aspect_ratio : Double
  fill_ratio : Double
  edge_density : Double
  file_name : String
}

///|
pub extend ExtractedImage with Eq::{not_equal, equal}

///|
pub extend ExtractedImage with @debug.Debug::{to_repr}

///|
/// 检测水平表格线(基于形态学操作的简化版)
pub fn detect_horizontal_table_lines(
  binary_img : @types.Image,
  min_length~ : Int32 = 50,
  max_gap~ : Int32 = 3,
) -> Array[(Int32, Int32, Int32)] raise @types.LoadError {
  // 输入验证
  if binary_img.width <= 0 || binary_img.height <= 0 {
    raise @types.LoadError::DecodeFailed(
      "detect_horizontal_table_lines: 图像尺寸必须大于0",
    )
  }
  if binary_img.channels != 1 {
    raise @types.LoadError::DecodeFailed(
      "detect_horizontal_table_lines: 仅支持单通道二值图",
    )
  }
  let expected_size = binary_img.width * binary_img.height
  if binary_img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "detect_horizontal_table_lines: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      binary_img.data.length().to_string(),
    )
  }
  if min_length <= 0 {
    raise @types.LoadError::DecodeFailed(
      "detect_horizontal_table_lines: 最小线长必须大于0",
    )
  }
  if max_gap < 0 {
    raise @types.LoadError::DecodeFailed(
      "detect_horizontal_table_lines: 最大间隙不能为负",
    )
  }
  let min_len = min_length
  let max_g = max_gap
  let w = binary_img.width
  let h = binary_img.height
  let lines : Array[(Int32, Int32, Int32)] = []
  for y in 0..= min_len {
          lines.push((y, start_x, end_x))
        }
      } else {
        x += 1
      }
    }
  }
  // 合并相近的线(y 差 <= 2)
  let merged : Array[(Int32, Int32, Int32)] = []
  for line in lines {
    let mut found = false
    for i in 0.. mex { line.2 } else { mex }
        merged[i] = (new_y, new_sx, new_ex)
        found = true
        break
      }
    }
    if !found {
      merged.push(line)
    }
  }
  merged
}

///|
/// 检测垂直表格线
pub fn detect_vertical_table_lines(
  binary_img : @types.Image,
  min_length~ : Int32 = 50,
  max_gap~ : Int32 = 3,
) -> Array[(Int32, Int32, Int32)] raise @types.LoadError {
  // 输入验证
  if binary_img.width <= 0 || binary_img.height <= 0 {
    raise @types.LoadError::DecodeFailed(
      "detect_vertical_table_lines: 图像尺寸必须大于0",
    )
  }
  if binary_img.channels != 1 {
    raise @types.LoadError::DecodeFailed(
      "detect_vertical_table_lines: 仅支持单通道二值图",
    )
  }
  let expected_size = binary_img.width * binary_img.height
  if binary_img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "detect_vertical_table_lines: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      binary_img.data.length().to_string(),
    )
  }
  if min_length <= 0 {
    raise @types.LoadError::DecodeFailed(
      "detect_vertical_table_lines: 最小线长必须大于0",
    )
  }
  if max_gap < 0 {
    raise @types.LoadError::DecodeFailed(
      "detect_vertical_table_lines: 最大间隙不能为负",
    )
  }
  let min_len = min_length
  let max_g = max_gap
  let w = binary_img.width
  let h = binary_img.height
  let lines : Array[(Int32, Int32, Int32)] = []
  for x in 0..= min_len {
          lines.push((x, start_y, end_y))
        }
      } else {
        y += 1
      }
    }
  }
  // 合并相近的线
  let merged : Array[(Int32, Int32, Int32)] = []
  for line in lines {
    let mut found = false
    for i in 0.. mey { line.2 } else { mey }
        merged[i] = (new_x, new_sy, new_ey)
        found = true
        break
      }
    }
    if !found {
      merged.push(line)
    }
  }
  merged
}

///|
/// 检测表格线交叉点
pub fn find_line_intersections(
  h_lines : Array[(Int32, Int32, Int32)],
  v_lines : Array[(Int32, Int32, Int32)],
) -> Array[(Int32, Int32)] {
  let intersections : Array[(Int32, Int32)] = []
  for _tup0 in h_lines {
    let (hy, hsx, hex) = _tup0
    for _tup1 in v_lines {
      let (vx, vsy, vey) = _tup1
      if vx >= hsx && vx <= hex && hy >= vsy && hy <= vey {
        intersections.push((vx, hy))
      }
    }
  }
  intersections
}

///|
/// 完整表格检测
pub fn detect_table_enhanced(
  binary_img : @types.Image,
  min_table_size~ : Int32 = 100,
) -> Array[EnhancedTableResult] raise @types.LoadError {
  // 输入验证
  if binary_img.width <= 0 || binary_img.height <= 0 {
    raise @types.LoadError::DecodeFailed(
      "detect_table_enhanced: 图像尺寸必须大于0",
    )
  }
  if binary_img.channels != 1 {
    raise @types.LoadError::DecodeFailed(
      "detect_table_enhanced: 仅支持单通道二值图",
    )
  }
  let expected_size = binary_img.width * binary_img.height
  if binary_img.data.length() != expected_size {
    raise @types.LoadError::DecodeFailed(
      "detect_table_enhanced: 数据大小不匹配,期望 " +
      expected_size.to_string() +
      ",实际 " +
      binary_img.data.length().to_string(),
    )
  }
  if min_table_size <= 0 {
    raise @types.LoadError::DecodeFailed(
      "detect_table_enhanced: 最小表格尺寸必须大于0",
    )
  }
  let min_size = min_table_size
  let h_lines = detect_horizontal_table_lines(
    binary_img,
    min_length=50,
    max_gap=3,
  )
  let v_lines = detect_vertical_table_lines(
    binary_img,
    min_length=50,
    max_gap=3,
  )
  let intersections = find_line_intersections(h_lines, v_lines)

  let results : Array[EnhancedTableResult] = []

  if h_lines.length() < 2 || v_lines.length() < 2 {
    return results
  }

  // 提取唯一的行 y 坐标和列 x 坐标
  let row_ys : Array[Int32] = []
  for _tup2 in h_lines {
    let (y, _, _) = _tup2
    let mut exists = false
    for ry in row_ys {
      if (ry - y).abs() <= 3 {
        exists = true
        break
      }
    }
    if !exists {
      row_ys.push(y)
    }
  }

  let col_xs : Array[Int32] = []
  for _tup3 in v_lines {
    let (x, _, _) = _tup3
    let mut exists = false
    for cx in col_xs {
      if (cx - x).abs() <= 3 {
        exists = true
        break
      }
    }
    if !exists {
      col_xs.push(x)
    }
  }

  // 排序
  for i in 0.. row_ys[j + 1] {
        let temp = row_ys[j]
        row_ys[j] = row_ys[j + 1]
        row_ys[j + 1] = temp
      }
    }
  }
  for i in 0.. col_xs[j + 1] {
        let temp = col_xs[j]
        col_xs[j] = col_xs[j + 1]
        col_xs[j + 1] = temp
      }
    }
  }

  let num_rows = row_ys.length() - 1
  let num_cols = col_xs.length() - 1

  if num_rows < 1 || num_cols < 1 {
    return results
  }

  let table_x = col_xs[0]
  let table_y = row_ys[0]
  let table_width = col_xs[col_xs.length() - 1] - table_x
  let table_height = row_ys[row_ys.length() - 1] - table_y

  if table_width < min_size || table_height < min_size {
    return results
  }

  // 构建单元格
  let cells : Array[TableCellContent] = []
  for row in 0.. String {
  let mut md = ""
  // 表头
  if table.has_header && table.rows > 0 {
    md = md + "| "
    for col in 0.. String {
  for cell in table.cells {
    if cell.row == row && cell.col == col {
      return cell.text
    }
  }
  ""
}

///|
/// 提取图片区域(增强版,支持多种图片类型判断)
pub fn extract_images_enhanced(
  binary_img : @types.Image,
  min_area~ : Int32 = 500,
) -> Array[ExtractedImage] {
  let min = min_area
  let w = binary_img.width
  let h = binary_img.height
  let images : Array[ExtractedImage] = []
  let visited : Array[Bool] = []
  for _ in 0..<(w * h) {
    visited.push(false)
  }
  for y in 0.. 0 {
          let cx_opt = stack_x.pop()
          let cy_opt = stack_y.pop()
          match cx_opt {
            Some(cx) =>
              match cy_opt {
                Some(cy) => {
                  area += 1
                  if cx < min_x {
                    min_x = cx
                  }
                  if cx > max_x {
                    max_x = cx
                  }
                  if cy < min_y {
                    min_y = cy
                  }
                  if cy > max_y {
                    max_y = cy
                  }
                  // 边缘检测:检查是否有白色邻域
                  let mut is_edge = false
                  let neighbors = [
                    (cx - 1, cy),
                    (cx + 1, cy),
                    (cx, cy - 1),
                    (cx, cy + 1),
                  ]
                  for _tup4 in neighbors {
                    let (nx, ny) = _tup4
                    if nx >= 0 && nx < w && ny >= 0 && ny < h {
                      let nidx = ny * w + nx
                      if !visited[nidx] && binary_img.data[nidx].to_int() >= 128 {
                        is_edge = true
                      }
                      if !visited[nidx] && binary_img.data[nidx].to_int() < 128 {
                        visited[nidx] = true
                        stack_x.push(nx)
                        stack_y.push(ny)
                      }
                    }
                  }
                  if is_edge {
                    edge_pixels += 1
                  }
                }
                None => ()
              }
            None => ()
          }
        }
        let region_width = max_x - min_x + 1
        let region_height = max_y - min_y + 1
        if area >= min && region_width > 20 && region_height > 20 {
          let fill_ratio = area.to_double() /
            (region_width * region_height).to_double()
          let aspect_ratio = region_width.to_double() /
            region_height.to_double()
          let edge_density = edge_pixels.to_double() / area.to_double()
          // 图片类型判断
          let image_type = if fill_ratio > 0.9 &&
            aspect_ratio > 0.8 &&
            aspect_ratio < 1.2 {
            "logo"
          } else if fill_ratio > 0.8 {
            "diagram"
          } else if fill_ratio > 0.5 && edge_density > 0.3 {
            "chart"
          } else if aspect_ratio > 2.0 || aspect_ratio < 0.5 {
            "signature"
          } else {
            "photo"
          }
          let file_name = "image_" + images.length().to_string() + ".png"
          images.push(ExtractedImage::{
            x: min_x,
            y: min_y,
            width: region_width,
            height: region_height,
            image_type,
            confidence: 0.75,
            aspect_ratio,
            fill_ratio,
            edge_density,
            file_name,
          })
        }
      }
    }
  }
  images
}

///|
/// 生成图片提取报告
pub fn generate_image_extraction_report(
  images : Array[ExtractedImage],
) -> String {
  let mut report = "## 图片提取报告\n\n"
  report = report +
    "共提取 " +
    images.length().to_string() +
    " 张图片\n\n"
  report = report +
    "| 序号 | 类型 | 位置 | 尺寸 | 宽高比 | 填充率 | 置信度 | 文件名 |\n"
  report = report +
    "|------|------|------|------|--------|--------|--------|--------|\n"
  for i in 0.. Array[(String, Int32)] {
  let total_tables = tables.length()
  let mut total_cells = 0
  let mut total_rows = 0
  let mut total_cols = 0
  let mut with_header = 0
  for table in tables {
    total_cells += table.cells.length()
    total_rows += table.rows
    total_cols += table.cols
    if table.has_header {
      with_header += 1
    }
  }
  [
    ("表格总数", total_tables),
    ("单元格总数", total_cells),
    ("总行数", total_rows),
    ("总列数", total_cols),
    ("含表头表格", with_header),
  ]
}