///|
/// # 图像加载/保存统一入口 Image Load/Save Unified Entry
///
/// 通过 magic bytes 自动检测图像格式,并委托 codec/color 包进行解码和通道转换。 Automatically detects image format via magic bytes, and delegates to codec/color packages for decoding and channel conversion.
///
/// 核心函数 Core functions:
/// - `detect_format` - 检测图像格式 Detect image format
/// - `load_from_bytes` - 从字节流加载图像 Load image from byte stream
/// - `save_to_bytes` - 保存图像为字节流 Save image to byte stream
/// - `load_image_info` - 加载图像信息(不含像素数据)Load image info (no pixel data)
///
/// 注意 Notes:
/// - TGA 无固定 magic bytes,需显式调用 @codec.decode_tga_pure TGA has no fixed magic bytes, must explicitly call @codec.decode_tga_pure
/// - HDR 返回 ImageF(浮点图像),需显式调用 @codec.decode_hdr_pure HDR returns ImageF (float image), must explicitly call @codec.decode_hdr_pure

// lib 包:统一分派入口(格式分派层)
// 职责:通过 magic bytes 检测图像格式,并委托 pure/codec 进行解码、pure/color 进行通道转换
// 注意:TGA 无固定 magic bytes,需显式调用 @codec.decode_tga_pure
//       HDR 返回 ImageF(浮点图像),需显式调用 @codec.decode_hdr_pure

///|
pub type ImageFormat = @types.ImageFormat

///|
/// 通过 magic bytes 检测图像格式 - BMP "BM"、QOI "qoif"、PNM "P5"/"P6"、PSD "8BPS"、GIF "GIF87a"/"GIF89a"

/// - PNG 8字节签名、JPEG SOI 0xFF 0xD8 - WebP: RIFF....WEBP

///|
/// - ICNS: 前4字节 "icns"
/// - TIFF: 字节序标记 + magic 0x002A
/// - ICO/CUR: 前4字节 00 00 01 00
/// - TGA 无固定 magic bytes,按头部字段(color map / image type / bpp / 宽高)保守判定
pub fn detect_format(data : Bytes) -> @types.ImageFormat {
  let len = data.length()
  if len < 2 {
    return @types.ImageFormat::Unknown
  }
  // PNG: 8字节签名
  if len >= 8 &&
    data[0].to_int() == 0x89 &&
    data[1].to_int() == 0x50 &&
    data[2].to_int() == 0x4E &&
    data[3].to_int() == 0x47 &&
    data[4].to_int() == 0x0D &&
    data[5].to_int() == 0x0A &&
    data[6].to_int() == 0x1A &&
    data[7].to_int() == 0x0A {
    // 检查是否 APNG(含 acTL chunk)
    if @codec.is_apng_format(data) {
      return @types.ImageFormat::Apng
    }
    return @types.ImageFormat::Png
  }
  // JPEG: SOI marker
  if data[0].to_int() == 0xFF && data[1].to_int() == 0xD8 {
    return @types.ImageFormat::Jpeg
  }
  // BMP: "BM"
  if data[0].to_int() == 0x42 && data[1].to_int() == 0x4D {
    return @types.ImageFormat::Bmp
  }
  // QOI: "qoif"
  if len >= 4 &&
    data[0].to_int() == 0x71 &&
    data[1].to_int() == 0x6F &&
    data[2].to_int() == 0x69 &&
    data[3].to_int() == 0x66 {
    return @types.ImageFormat::Qoi
  }
  // PNM: "P5"/"P6"
  if data[0].to_int() == 0x50 &&
    data[1].to_int() >= 0x35 &&
    data[1].to_int() <= 0x36 {
    return @types.ImageFormat::Pnm
  }
  // PSD: "8BPS"
  if len >= 4 &&
    data[0].to_int() == 0x38 &&
    data[1].to_int() == 0x42 &&
    data[2].to_int() == 0x50 &&
    data[3].to_int() == 0x53 {
    return @types.ImageFormat::Psd
  }
  // GIF: "GIF87a" or "GIF89a"
  if len >= 6 &&
    data[0].to_int() == 0x47 &&
    data[1].to_int() == 0x49 &&
    data[2].to_int() == 0x46 {
    return @types.ImageFormat::Gif
  }
  // HDR: #?RADIANCE
  if len >= 10 &&
    data[0].to_int() == 0x23 &&
    data[1].to_int() == 0x3F &&
    data[2].to_int() == 0x52 {
    return @types.ImageFormat::Hdr
  }
  // WebP: RIFF....WEBP
  if len >= 12 &&
    data[0].to_int() == 0x52 &&
    data[1].to_int() == 0x49 &&
    data[2].to_int() == 0x46 &&
    data[3].to_int() == 0x46 &&
    data[8].to_int() == 0x57 &&
    data[9].to_int() == 0x45 &&
    data[10].to_int() == 0x42 &&
    data[11].to_int() == 0x50 {
    return @types.ImageFormat::Webp
  }
  // ICNS: 前4字节 "icns"
  if len >= 4 &&
    data[0].to_int() == 0x69 &&
    data[1].to_int() == 0x63 &&
    data[2].to_int() == 0x6E &&
    data[3].to_int() == 0x73 {
    return @types.ImageFormat::Icns
  }
  // TIFF: 字节序标记 (II=0x4949 LE, MM=0x4D4D BE) + magic 42 (offset 2-3)
  if (data[0].to_int() == 0x49 && data[1].to_int() == 0x49) ||
    (data[0].to_int() == 0x4D && data[1].to_int() == 0x4D) {
    if len >= 4 &&
      (
        (data[2].to_int() == 0x2A && data[3].to_int() == 0x00) ||
        (data[2].to_int() == 0x00 && data[3].to_int() == 0x2A)
      ) {
      return @types.ImageFormat::Tiff
    }
  }
  // ICO/CUR: 00 00 XX 00 + 图像数量 (≥1) + 目录条目
  // XX = 01 (ICO) 或 02 (CUR),总长度至少 22 字节(6 头 + 16 目录条目)
  if len >= 22 &&
    data[0].to_int() == 0x00 &&
    data[1].to_int() == 0x00 &&
    (data[2].to_int() == 0x01 || data[2].to_int() == 0x02) &&
    data[3].to_int() == 0x00 &&
    data[4].to_int() != 0 { // 图像数量必须非零
    // 读取第一个目录条目的 width/height
    let width = data[6].to_int()
    let height = data[7].to_int()
    // CUR: width=0 且 height=0 表示热点坐标占位
    if data[2].to_int() == 0x02 && width == 0 && height == 0 {
      return @types.ImageFormat::Cur
    }
    return @types.ImageFormat::Ico
  }
  // JPEG-XL: 裸码流 0xFF 0x0A 或 ISOBMFF 容器
  if len >= 2 && data[0].to_int() == 0xFF && data[1].to_int() == 0x0A {
    return @types.ImageFormat::JpegXl
  }
  if len >= 12 &&
    data[0].to_int() == 0x00 &&
    data[1].to_int() == 0x00 &&
    data[2].to_int() == 0x00 &&
    data[3].to_int() == 0x0C &&
    data[4].to_int() == 0x4A &&
    data[5].to_int() == 0x58 &&
    data[6].to_int() == 0x4C &&
    data[7].to_int() == 0x20 {
    return @types.ImageFormat::JpegXl
  }
  // AVIF/HEIF: ftyp box (bytes 4-7 = "ftyp")
  if len >= 12 &&
    data[4].to_int() == 0x66 &&
    data[5].to_int() == 0x74 &&
    data[6].to_int() == 0x79 &&
    data[7].to_int() == 0x70 {
    let b8 = data[8].to_int()
    let b9 = data[9].to_int()
    let b10 = data[10].to_int()
    let b11 = data[11].to_int()
    // AVIF: "avif" (0x61 0x76 0x69 0x66) or "avis" (0x61 0x76 0x69 0x73)
    if b8 == 0x61 && b9 == 0x76 && b10 == 0x69 && (b11 == 0x66 || b11 == 0x73) {
      return @types.ImageFormat::Avif
    }
    // HEIF: "heic", "heix", "hevc", "mif1"
    if (b8 == 0x68 && b9 == 0x65 && b10 == 0x69 && (b11 == 0x63 || b11 == 0x78)) ||
      (b8 == 0x68 && b9 == 0x65 && b10 == 0x76 && b11 == 0x63) ||
      (b8 == 0x6D && b9 == 0x69 && b10 == 0x66 && b11 == 0x31) {
      return @types.ImageFormat::Heif
    }
  }
  // TGA:无强魔数,放最后用头部字段判定(前面所有 magic 都已排除)
  if @codec.is_tga_format(data) {
    return @types.ImageFormat::Tga
  }
  @types.ImageFormat::Unknown
}

///|
/// 自动格式分派解码(pure 侧统一入口),根据 magic bytes 检测格式并委托对应 pure 解码器
/// - TGA 无固定魔数,按头部字段保守判定(`@codec.is_tga_format`),命中则走 `decode_tga_pure`
/// - HDR 返回 ImageF,需显式调用 @codec.decode_hdr_pure
/// - APNG 与 PNG 共享签名,需显式调用 decode_apng_pure
/// - 未识别格式 raise LoadError::DecodeFailed Auto-format dispatch decoding (pure side unified entry), Detects format from magic bytes and delegates to corresponding pure decoder

///|
/// ```mbt check
/// test "doc_load_from_bytes_auto_bmp" {
///   try {
///     let img = @lib.load_from_bytes_auto(@types.DOC_TEST_BMP_1X1)
///     assert_eq(img.width, 1)
///     assert_eq(img.channels, 3)
///   } catch {
///     _ => assert_true(false)
///   }
/// }
/// ```
pub fn load_from_bytes_auto(
  data : Bytes,
  req_channels~ : Int32? = None,
) -> @types.Image raise @types.LoadError {
  let img = match detect_format(data) {
    @types.ImageFormat::Png => @codec.decode_png_pure(data, req_channels~)
    @types.ImageFormat::Jpeg => @codec.decode_jpeg_pure(data)
    @types.ImageFormat::Bmp => @codec.decode_bmp_pure(data)
    @types.ImageFormat::Qoi => @codec.decode_qoi_pure(data)
    @types.ImageFormat::Pnm => @codec.decode_pnm_pure(data)
    @types.ImageFormat::Psd => @codec.decode_psd_pure(data)
    @types.ImageFormat::Gif => @codec.decode_gif_pure(data)
    @types.ImageFormat::Webp => @codec.decode_webp_pure(data)
    @types.ImageFormat::Hdr =>
      raise @types.LoadError::DecodeFailed(
        "HDR 格式需要显式调用 decode_hdr_pure",
      )
    @types.ImageFormat::Tga => @codec.decode_tga_pure(data)
    @types.ImageFormat::Tiff => @codec.decode_tiff_pure(data)
    @types.ImageFormat::Ico => @codec.decode_ico_pure(data)
    @types.ImageFormat::Cur => @codec.decode_cur_pure(data)
    @types.ImageFormat::Icns => @codec.decode_icns_pure(data)
    @types.ImageFormat::Apng => {
      let anim = @codec.decode_apng_pure(data)
      if anim.frames.length() == 0 {
        raise @types.LoadError::DecodeFailed("APNG 无帧")
      }
      anim.frames[0]
    }
    @types.ImageFormat::Avif => @codec.avif_decode(data)
    @types.ImageFormat::Heif => @codec.heif_decode(data)
    @types.ImageFormat::JpegXl => @codec.jpegxl_decode(data)
    @types.ImageFormat::Unknown =>
      raise @types.LoadError::DecodeFailed(
        "不支持或无法识别的格式(TGA 无 magic bytes,需显式调用 decode_tga_pure)",
      )
    @types.ImageFormat::.. =>
      raise @types.LoadError::DecodeFailed("不支持或无法识别的格式")
  }
  match req_channels {
    Some(n) => @color.convert_channels_pure(img, n)
    None => img
  }
}

///|
/// 16-bit 自动格式分派解码(纯 MoonBit,全目标可用)
/// 根据格式委托对应 16-bit 解码器,输出 Image16(little-endian uint16)
/// - PNG: 支持 8-bit 上采样和原生 16-bit
/// - PNM: 支持 8-bit 上采样和原生 16-bit
/// - 其他格式不支持 16-bit
/// 注意:req_channels 仅对 PNG 生效,PNM 分支不传递 req_channels
pub fn load_16_from_bytes_auto(
  data : Bytes,
  req_channels~ : Int32? = None,
) -> @types.Image16 raise @types.LoadError {
  match detect_format(data) {
    @types.ImageFormat::Png => @codec.decode_png_16_pure(data, req_channels~)
    @types.ImageFormat::Pnm => @codec.decode_pnm_16_pure(data)
    _ =>
      raise @types.LoadError::DecodeFailed(
        "16-bit 解码不支持此格式,仅支持 PNG 和 PNM",
      )
  }
}

///|
/// QOI 编码委托
/// QOI 编码委托 QOI encoding delegation
///
/// 错误 Errors:
/// - `LoadError::EncodeFailed` - channels 不为 3 或 4 Channels not 3 or 4
pub fn encode_qoi(img : @types.Image) -> Bytes raise @types.LoadError {
  @codec.encode_qoi_pure(img)
}

///|
/// PNM 编码委托(channels<=1 → PGM else → PPM)
pub fn encode_pnm_auto(img : @types.Image) -> Bytes {
  @codec.encode_pnm_pure(img)
}

///|
/// PPM 编码委托
pub fn encode_ppm_auto(img : @types.Image) -> Bytes {
  @codec.encode_ppm_pure(img)
}

///|
/// PGM 编码委托
pub fn encode_pgm_auto(img : @types.Image) -> Bytes {
  @codec.encode_pgm_pure(img)
}

///|
/// GIF 编码委托
/// GIF 编码委托 GIF encoding delegation
///
/// 错误 Errors:
/// - `LoadError::EncodeFailed` - channels 不为 3 或 4 Channels not 3 or 4
pub fn encode_gif(img : @types.Image) -> Bytes raise @types.LoadError {
  @codec.encode_gif_pure(img)
}

///|
/// PNG 编码委托
pub fn encode_png(img : @types.Image) -> Bytes {
  @codec.encode_png_pure(img)
}

///|
/// JPEG 编码委托
/// JPEG 编码委托 JPEG encoding delegation
///
/// 错误 Errors:
/// - `LoadError::EncodeFailed` - 尺寸无效、channels 不支持 Invalid dimensions, unsupported channels
pub fn encode_jpeg(img : @types.Image) -> Bytes raise @types.LoadError {
  @codec.encode_jpeg_pure(img)
}

///|
/// 渐进式 JPEG 编码委托(SOF2)。
/// Progressive JPEG encoding delegation (SOF2).
///
/// 参数 Parameters:
/// - `img` - 输入图像;1 通道按灰度复制到三通道
/// - `quality` - 1–100,50 等价标准量化表
///
/// 错误 Errors:
/// - `LoadError::EncodeFailed` - 尺寸无效、或像素数超过 2,000,000(系数缓存上限)
pub fn encode_jpeg_progressive(
  img : @types.Image,
  quality : Int32,
) -> Bytes raise @types.LoadError {
  @codec.encode_jpeg_progressive(img, quality)
}

///|
/// 渐进式 JPEG 编码委托(SOF2,4:2:0 色度下采样)。
/// Progressive JPEG encoding with 4:2:0 chroma subsampling.
///
/// 参数 Parameters:
/// - `img` - 输入图像;1 通道按灰度处理
/// - `quality` - 1–100,50 等价标准量化表
///
/// 错误 Errors:
/// - `LoadError::EncodeFailed` - 尺寸无效、或像素数超过 2,000,000(系数缓存上限)
pub fn encode_jpeg_progressive_420(
  img : @types.Image,
  quality : Int32,
) -> Bytes raise @types.LoadError {
  @codec.encode_jpeg_progressive_420(img, quality)
}

///|
/// 渐进式 JPEG 编码委托(SOF2,4:2:0,**扫描脚本可配置**)。
///
/// `script` 给出每条扫描的分量集与 `Ss/Se/Ah/Al`;`@codec.jpeg_progressive_script_libjpeg()`
/// 返回 libjpeg `jpeg_simple_progression()` 的 10 段默认脚本,
/// `@codec.jpeg_progressive_script_eight()` 为 0.1.30 固定 8 段等价脚本。
///
/// 错误 Errors:
/// - `LoadError::EncodeFailed` - 尺寸无效、像素数超上限、脚本非法
pub fn encode_jpeg_progressive_420_scripted(
  img : @types.Image,
  quality : Int32,
  script : Array[@codec.JpegProgScan],
) -> Bytes raise @types.LoadError {
  @codec.encode_jpeg_progressive_420_scripted(img, quality, script)
}

///|
/// libjpeg 默认(10 段)progressive 扫描脚本。
pub fn jpeg_progressive_script_libjpeg() -> Array[@codec.JpegProgScan] {
  @codec.jpeg_progressive_script_libjpeg()
}

///|
/// 0.1.30 固定 8 段扫描脚本(DC 首扫 Al=1 → 3×AC 首扫 → DC 细化 → 3×AC 细化)。
pub fn jpeg_progressive_script_eight() -> Array[@codec.JpegProgScan] {
  @codec.jpeg_progressive_script_eight()
}

///|
/// HDR 编码委托
/// HDR 编码委托 HDR encoding delegation
///
/// 错误 Errors:
/// - `LoadError::EncodeFailed` - channels 不为 3 Channels not 3
pub fn encode_hdr(img : @types.ImageF) -> Bytes raise @types.LoadError {
  @codec.encode_hdr_pure(img)
}

///|
/// BMP 编码委托
pub fn encode_bmp(img : @types.Image) -> Bytes {
  @codec.encode_bmp_pure(img)
}

///|
/// TGA 编码委托
pub fn encode_tga(img : @types.Image) -> Bytes {
  @codec.encode_tga_pure(img)
}

///|
/// WebP 无损编码委托(VP8L)
///
/// 下游之所以需要这个别名:`save_image_auto(img, ImageFormat::Webp)` 能用,但很多人会先
/// `import walkzzz/image.codec/lib` 写"只用 lib"的代码,再去文档里找 webp 编码函数——
/// 而真正的实现在 `image.codec/codec`。这里给一条 `@lib` 就能拿到的入口,省一次 import。
pub fn encode_webp_lossless(img : @types.Image) -> Bytes raise @types.LoadError {
  @codec.encode_webp_lossless(img)
}

///|
/// WebP 解码委托(统一走 RFC 9649 合规的 VP8L 路径,palette / predictor / cross-color 全支持;
/// 有损 VP8 产物仍会报 `unsupported`,那是另一条待办)
pub fn decode_webp(data : Bytes) -> @types.Image raise @types.LoadError {
  @codec.decode_webp_pure(data)
}

///|
/// 统一保存 API:按指定格式自动分派编码
/// - 支持:PNG/JPEG/BMP/QOI/PNM/GIF/TGA/TIFF/ICO/CUR/ICNS/WebP
/// - 不支持:HDR(需 ImageF,用 encode_hdr)、APNG(需 PngAnimation)、AVIF/HEIF/JPEG-XL/PSD(无编码器)
pub fn save_image_auto(
  img : @types.Image,
  format : @types.ImageFormat,
) -> Bytes raise @types.LoadError {
  match format {
    @types.ImageFormat::Png => @codec.encode_png_pure(img)
    @types.ImageFormat::Jpeg => @codec.encode_jpeg_pure(img)
    @types.ImageFormat::Bmp => @codec.encode_bmp_pure(img)
    @types.ImageFormat::Qoi => @codec.encode_qoi_pure(img)
    @types.ImageFormat::Pnm => @codec.encode_pnm_pure(img)
    @types.ImageFormat::Gif => @codec.encode_gif_pure(img)
    @types.ImageFormat::Tga => @codec.encode_tga_pure(img)
    @types.ImageFormat::Tiff => @codec.encode_tiff_pure(img)
    @types.ImageFormat::Ico => @codec.encode_ico_pure(img)
    @types.ImageFormat::Cur => @codec.encode_cur_pure(img)
    @types.ImageFormat::Icns => @codec.encode_icns_pure(img)
    @types.ImageFormat::Webp => @codec.encode_webp_lossless(img)
    _ =>
      raise @types.LoadError::EncodeFailed(
        "不支持此格式的编码(HDR 需 ImageF,APNG 需 PngAnimation,AVIF/HEIF/JPEG-XL/PSD 无编码器)",
      )
  }
}

///|
/// 带质量参数的统一保存 API
/// - WebP: 走 VP8L 无损编码,`quality` 参数被忽略(无损)
/// - JPEG: `quality` 1–100 生效(50 = 标准量化表)
/// - 其他格式: quality 参数被忽略,使用默认质量
/// - 不支持的格式 raise
pub fn save_image_with_quality(
  img : @types.Image,
  format : @types.ImageFormat,
  quality : Int32,
) -> Bytes raise @types.LoadError {
  match format {
    @types.ImageFormat::Webp => @codec.encode_webp_lossless(img)
    @types.ImageFormat::Png => @codec.encode_png_pure(img)
    @types.ImageFormat::Jpeg => @codec.encode_jpeg_with_quality(img, quality)
    @types.ImageFormat::Bmp => @codec.encode_bmp_pure(img)
    @types.ImageFormat::Qoi => @codec.encode_qoi_pure(img)
    @types.ImageFormat::Pnm => @codec.encode_pnm_pure(img)
    @types.ImageFormat::Gif => @codec.encode_gif_pure(img)
    @types.ImageFormat::Tga => @codec.encode_tga_pure(img)
    @types.ImageFormat::Tiff => @codec.encode_tiff_pure(img)
    @types.ImageFormat::Ico => @codec.encode_ico_pure(img)
    @types.ImageFormat::Cur => @codec.encode_cur_pure(img)
    @types.ImageFormat::Icns => @codec.encode_icns_pure(img)
    _ => raise @types.LoadError::EncodeFailed("不支持此格式的编码")
  }
}

///|
/// Float 自动格式分派加载,HDR → decode_hdr_pure 返回 ImageF,其他格式不支持 Float 加载 raise Float auto-format dispatch loading, HDR → decode_hdr_pure returns ImageF, Other formats do not support Float loading, raises

///|
/// 参数 Parameters:
/// - `data` - 字节流 Byte stream
///
/// 返回 Return:
/// - ImageF(HDR 解码结果)ImageF (HDR decode result)
///
/// 错误 Errors:
/// - `LoadError::DecodeFailed` - 非 HDR 格式、HDR 头无效 Non-HDR format, invalid HDR header
/// @see load_any 基础版本,本函数为 ImageF 变体
pub fn load_any_f(data : Bytes) -> @types.ImageF raise @types.LoadError {
  match detect_format(data) {
    @types.ImageFormat::Hdr => @codec.decode_hdr_pure(data)
    _ =>
      raise @types.LoadError::DecodeFailed(
        "Float 加载不支持此格式,仅支持 HDR",
      )
  }
}

///|
/// Float 自动格式分派保存,HDR → encode_hdr_pure,其他格式不支持 Float 保存 raise
/// @see save_any 基础版本,本函数为 ImageF 变体
pub fn save_any_f(
  img : @types.ImageF,
  format : @types.ImageFormat,
) -> Bytes raise @types.LoadError {
  match format {
    @types.ImageFormat::Hdr => @codec.encode_hdr_pure(img)
    _ =>
      raise @types.LoadError::EncodeFailed(
        "Float 保存不支持此格式,仅支持 HDR",
      )
  }
}

///|
/// 查询格式是否支持 16-bit 加载,PNG/PNM → true,其他 → false
pub fn format_supports_16bit(format : @types.ImageFormat) -> Bool {
  match format {
    @types.ImageFormat::Png => true
    @types.ImageFormat::Pnm => true
    _ => false
  }
}

///|
/// 查询格式是否支持 Float 加载/保存,HDR → true,其他 → false
pub fn format_supports_float(format : @types.ImageFormat) -> Bool {
  match format {
    @types.ImageFormat::Hdr => true
    _ => false
  }
}