///|
/// # 透视变换 perspective
///
/// 图像处理算法模块
/// 图像处理算法模块 Image processing algorithm module
// 透视变换(纯 MoonBit):get_perspective_transform + warp_perspective

///|
/// 3×3 透视变换矩阵 (m00, m01, m02, m10, m11, m12, m20, m21, m22)
pub(all) struct PerspectiveMatrix {
  m00 : Float
  m01 : Float
  m02 : Float
  m10 : Float
  m11 : Float
  m12 : Float
  m20 : Float
  m21 : Float
  m22 : Float
}

///|
/// 高斯消元法求解线性方程组 Ax=b,A 为 n×n 矩阵,b 为 n 维向量
fn solve_linear_system(
  a : Array[Array[Float]],
  b : Array[Float],
  n : Int32,
) -> Array[Float]? {
  let mat : Array[Array[Float]] = Array::make(n, [])
  for i in 0.. mat[pivot][col].abs() {
        pivot = row
      }
    }
    if mat[pivot][col].abs() < 0.0000000001F {
      return None
    }
    if pivot != col {
      let tmp = mat[pivot]
      mat[pivot] = mat[col]
      mat[col] = tmp
    }
    // 消元
    for row in (col + 1).. PerspectiveMatrix? {
  if src.length() != 4 || dst.length() != 4 {
    return None
  }
  // 构建 8×8 线性方程组
  let a : Array[Array[Float]] = Array::make(8, [])
  let b : Array[Float] = Array::make(8, 0.0F)
  for i in 0..<4 {
    let (sx, sy) = src[i]
    let (dx, dy) = dst[i]
    // 方程 1: m00*sx + m01*sy + m02 - m20*sx*dx - m21*sy*dx = dx
    a[i * 2] = [sx, sy, 1.0F, 0.0F, 0.0F, 0.0F, -sx * dx, -sy * dx]
    b[i * 2] = dx
    // 方程 2: m10*sx + m11*sy + m12 - m20*sx*dy - m21*sy*dy = dy
    a[i * 2 + 1] = [0.0F, 0.0F, 0.0F, sx, sy, 1.0F, -sx * dy, -sy * dy]
    b[i * 2 + 1] = dy
  }
  let sol = solve_linear_system(a, b, 8)
  match sol {
    None => None
    Some(v) =>
      Some(PerspectiveMatrix::{
        m00: v[0],
        m01: v[1],
        m02: v[2],
        m10: v[3],
        m11: v[4],
        m12: v[5],
        m20: v[6],
        m21: v[7],
        m22: 1.0F,
      })
  }
}

///|
/// 透视变换。使用 3×3 矩阵将图像变换到 new_w × new_h。
/// 采用 dst→src 映射 + 双线性插值。
pub fn warp_perspective(
  img : @types.Image,
  matrix : PerspectiveMatrix,
  new_w : Int32,
  new_h : Int32,
) -> @types.Image {
  let ch = img.channels
  let w = img.width
  let h = img.height
  let data_int : Array[Int32] = Array::make(w * h * ch, 0)
  for i in 0..<(w * h * ch) {
    data_int[i] = img.data[i].to_int()
  }
  let out : Array[Byte] = Array::make(new_w * new_h * ch, b'\x00')
  for dy in 0.. Int32 {
  let x0 = x.to_int()
  let y0 = y.to_int()
  let w1 = w - 1
  let h1 = h - 1
  let x0c = x0.clamp(min=0, max=w1)
  let y0c = y0.clamp(min=0, max=h1)
  let x1 = (x0 + 1).clamp(min=0, max=w1)
  let y1 = (y0 + 1).clamp(min=0, max=h1)
  let fx = x - Float::from_int(x0)
  let fy = y - Float::from_int(y0)
  let p00 = data[(y0c * w + x0c) * ch + c]
  let p10 = data[(y0c * w + x1) * ch + c]
  let p01 = data[(y1 * w + x0c) * ch + c]
  let p11 = data[(y1 * w + x1) * ch + c]
  let top = Float::from_int(p00) * (1.0F - fx) + Float::from_int(p10) * fx
  let bot = Float::from_int(p01) * (1.0F - fx) + Float::from_int(p11) * fx
  (top * (1.0F - fy) + bot * fy + 0.5F).to_int().clamp(min=0, max=255)
}