///|
/// Pure MoonBit streaming ZIP extractor backed by `moonbitlang/core/compress/flate`.
/// - `ZIP_STORED` entries (including 375 MiB precompressed sound/png/gz assets) stream
///   disk-to-disk in 64 KiB chunks with constant memory.
/// - `ZIP_DEFLATED` entries inflate via `@flate.inflate_exact`.

///|
priv struct ZipEntryMeta {
  name : String
  method_id : Int32
  comp_size : Int64
  uncomp_size : Int64
  local_header_offset : Int64
}

///|
fn read_u16_le(b : Bytes, off : Int32) -> Int32 {
  b[off].to_int() | (b[off + 1].to_int() << 8)
}

///|
fn read_u32_le(b : Bytes, off : Int32) -> Int64 {
  b[off].to_int64() |
  (b[off + 1].to_int64() << 8) |
  (b[off + 2].to_int64() << 16) |
  (b[off + 3].to_int64() << 24)
}

///|
fn normalize_zip_entry_path(raw : String) -> String? {
  let unified = raw.replace_all(old="\\", new="/")
  if unified.is_empty() || unified.has_prefix("/") {
    return None
  }
  let parts : Array[String] = []
  for seg_view in unified.split("/") {
    let seg = seg_view.to_owned()
    if seg.is_empty() || seg == "." {
      continue
    }
    if seg == ".." || seg.contains(":") {
      return None
    }
    parts.push(seg)
  }
  if parts.is_empty() {
    return None
  }
  Some(parts.join("/"))
}

///|
fn parent_dir(path : String) -> String {
  match path.rev_find("/") {
    Some(idx) if idx > 0 => path[:idx].to_owned()
    _ => ""
  }
}

///|
async fn ensure_dir_cached(dir : String, seen : Map[String, Bool]) -> Unit {
  if dir.is_empty() || seen.contains(dir) {
    return
  }
  @fs.mkdir(dir, recursive=true, allow_exist=true)
  seen[dir] = true
}

///|
fn find_eocd(tail : Bytes) -> (Int32, Int64, Int64)? {
  let len = tail.length()
  if len < 22 {
    return None
  }
  let mut i = len - 22
  while i >= 0 {
    if tail[i] == b'\x50' &&
      tail[i + 1] == b'\x4b' &&
      tail[i + 2] == b'\x05' &&
      tail[i + 3] == b'\x06' {
      let comment_len = read_u16_le(tail, i + 20)
      if i + 22 + comment_len == len {
        let entry_count = read_u16_le(tail, i + 10)
        let cd_size = read_u32_le(tail, i + 12)
        let cd_offset = read_u32_le(tail, i + 16)
        return Some((entry_count, cd_size, cd_offset))
      }
    }
    i -= 1
  }
  None
}

///|
fn parse_central_directory(
  cd : Bytes,
  expected_entries : Int32,
) -> Array[ZipEntryMeta] raise Failure {
  let out : Array[ZipEntryMeta] = []
  let mut pos = 0
  let len = cd.length()
  while pos + 46 <= len {
    if cd[pos] != b'\x50' ||
      cd[pos + 1] != b'\x4b' ||
      cd[pos + 2] != b'\x01' ||
      cd[pos + 3] != b'\x02' {
      fail("invalid ZIP central directory signature at offset \{pos}")
    }
    let method_id = read_u16_le(cd, pos + 10)
    let comp_size = read_u32_le(cd, pos + 20)
    let uncomp_size = read_u32_le(cd, pos + 24)
    let name_len = read_u16_le(cd, pos + 28)
    let extra_len = read_u16_le(cd, pos + 30)
    let comment_len = read_u16_le(cd, pos + 32)
    let local_header_offset = read_u32_le(cd, pos + 42)
    let header_end = pos + 46 + name_len + extra_len + comment_len
    if header_end > len {
      fail("truncated ZIP central directory entry")
    }
    let name = @utf8.decode(cd[pos + 46:pos + 46 + name_len]) catch {
      _ => fail("invalid UTF-8 filename in ZIP central directory")
    }
    out.push({ name, method_id, comp_size, uncomp_size, local_header_offset, })
    pos = header_end
  }
  if expected_entries > 0 && out.length() != expected_entries {
    fail(
      "ZIP central directory entry count mismatch: expected \{expected_entries}, parsed \{out.length()}",
    )
  }
  out
}

///|
async fn extract_single_entry(
  f : @fs.File,
  entry : ZipEntryMeta,
  dest : String,
  buf : FixedArray[Byte],
) -> Unit {
  let lfh = f.read_exactly_at(30, position=entry.local_header_offset)
  if lfh[0] != b'\x50' ||
    lfh[1] != b'\x4b' ||
    lfh[2] != b'\x03' ||
    lfh[3] != b'\x04' {
    fail("invalid ZIP local header signature for \{entry.name}")
  }
  let name_len = read_u16_le(lfh, 26)
  let extra_len = read_u16_le(lfh, 28)
  let data_offset = entry.local_header_offset +
    30L +
    name_len.to_int64() +
    extra_len.to_int64()
  let out_file = @fs.open(dest, mode=WriteOnly, create_mode=CreateOrTruncate)
  defer out_file.close()
  if entry.method_id == 0 {
    // ZIP_STORED: stream disk-to-disk in 64 KiB chunks.
    let mut pos = data_offset
    let mut remaining = entry.comp_size
    while remaining > 0L {
      let want = if remaining > 65536L { 65536 } else { remaining.to_int() }
      let n = f.read_at(buf, position=pos, offset=0, len=want)
      if n <= 0 {
        fail("unexpected EOF extracting stored entry \{entry.name}")
      }
      out_file.write(Bytes::from_array(buf[:n]))
      pos += n.to_int64()
      remaining -= n.to_int64()
    }
  } else if entry.method_id == 8 {
    // ZIP_DEFLATED: read compressed payload and inflate via core/compress/flate.
    if entry.comp_size > 268435456L {
      fail("deflated entry too large: \{entry.name}")
    }
    let comp = f.read_exactly_at(entry.comp_size.to_int(), position=data_offset)
    let inflated = @flate.inflate_exact(comp[:]) catch {
      _ => fail("DEFLATE decompression failed for \{entry.name}")
    }
    if entry.uncomp_size >= 0L &&
      inflated.length().to_int64() != entry.uncomp_size {
      fail(
        "uncompressed size mismatch for \{entry.name}: expected \{entry.uncomp_size}, got \{inflated.length()}",
      )
    }
    out_file.write(inflated)
  } else {
    fail(
      "unsupported ZIP compression method \{entry.method_id} for \{entry.name}",
    )
  }
}

///|
async fn extract_zip_to_staging(
  zip_path : String,
  staging_dir : String,
  label : String,
) -> Int32 {
  let f = @fs.open(zip_path, mode=ReadOnly)
  defer f.close()
  let fsize = f.size()
  let tail_len = if fsize > 65557L { 65557 } else { fsize.to_int() }
  let tail = f.read_exactly_at(tail_len, position=fsize - tail_len.to_int64())
  let (entry_count, cd_size, cd_offset) = match find_eocd(tail) {
    Some(v) => v
    None => fail("invalid ZIP archive (missing EOCD): \{zip_path}")
  }
  if cd_size <= 0L || cd_size > 67108864L || cd_offset < 0L {
    fail("invalid ZIP central directory range in \{zip_path}")
  }
  let cd_bytes = f.read_exactly_at(cd_size.to_int(), position=cd_offset)
  let entries = parse_central_directory(cd_bytes, entry_count)
  let created_dirs : Map[String, Bool] = Map([])
  created_dirs[staging_dir] = true
  let buf = FixedArray::make(65536, b'\x00')
  let mut total_files = 0
  for entry in entries {
    if !entry.name.has_suffix("/") {
      total_files += 1
    }
  }
  let mut count = 0
  let mut last_draw_ms = 0UL
  for entry in entries {
    if entry.name.has_suffix("/") {
      continue
    }
    let rel = match normalize_zip_entry_path(entry.name) {
      Some(p) => p
      None => fail("unsafe path inside zip: \{entry.name}")
    }
    let dest = "\{staging_dir}/\{rel}"
    ensure_dir_cached(parent_dir(dest), created_dirs)
    extract_single_entry(f, entry, dest, buf)
    count += 1
    let now_ms = @env.now()
    if now_ms >= last_draw_ms + 120UL || count == total_files {
      last_draw_ms = now_ms
      let bar = render_progress_bar(
        count.to_int64(),
        total_files.to_int64(),
        24,
      )
      let pct = if total_files > 0 { count * 100 / total_files } else { 100 }
      write_progress_inline(
        "  Extracting \{label} \{bar} \{pct}% (\{count}/\{total_files} files)",
        count == total_files,
      )
    }
  }
  count
}

///|
async fn extract_zip_streaming(
  zip_path : String,
  target_dir : String,
  label : String,
) -> Int32 {
  let staging_dir = "\{target_dir}.staging"
  if @fs.exists(staging_dir) {
    @fs.rmdir(staging_dir, recursive=true) catch {
      _ => ()
    }
  }
  @fs.mkdir(staging_dir, recursive=true, allow_exist=true)
  errdefer (@fs.rmdir(staging_dir, recursive=true) catch { _ => () })
  let count = extract_zip_to_staging(zip_path, staging_dir, label)
  if @fs.exists(target_dir) {
    @fs.rmdir(target_dir, recursive=true) catch {
      _ => ()
    }
  }
  @fs.rename(staging_dir, target_dir, replace=true)
  println("  Extracted \{count} files to \{target_dir}")
  count
}