#!/usr/bin/env python3
"""
split_cbz.py - Split a large CBZ (comic book zip) into smaller CBZ volumes.

Pages are kept in natural reading order (page2 before page10) and are never
cut in half; each part is filled up to roughly the target size. Data is
streamed in chunks, so a multi-GB file won't be loaded into memory.

Usage:
    python split_cbz.py "My Comic.cbz"                 # ~600 MB parts
    python split_cbz.py "My Comic.cbz" --size 500      # ~500 MB parts
    python split_cbz.py "My Comic.cbz" --parts 4       # 4 roughly equal parts
    python split_cbz.py "My Comic.cbz" -o out_folder
"""

import argparse
import re
import sys
import zipfile
from pathlib import Path

CHUNK = 4 * 1024 * 1024  # 4 MB copy buffer
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".avif", ".jxl", ".tif", ".tiff"}
# Small metadata files that get copied into every part
METADATA_NAMES = {"comicinfo.xml"}


def natural_key(s: str):
    """Sort 'page2' before 'page10'."""
    return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]


def plan_parts(entries, target_bytes):
    """Group entries into consecutive chunks of about target_bytes each."""
    parts, current, current_size = [], [], 0
    for info in entries:
        size = info.compress_size
        if current and current_size + size > target_bytes:
            parts.append(current)
            current, current_size = [], 0
        current.append(info)
        current_size += size
    if current:
        parts.append(current)
    return parts


def plan_n_parts(entries, n):
    """Split entries into exactly n consecutive chunks of roughly equal size.

    Each page goes to the part its midpoint falls into, measured by
    cumulative size, so the parts balance out instead of spilling over.
    """
    total = sum(i.compress_size for i in entries)
    parts = [[] for _ in range(n)]
    cum = 0
    for info in entries:
        mid = cum + info.compress_size / 2
        idx = min(n - 1, int(mid * n / total)) if total else 0
        parts[idx].append(info)
        cum += info.compress_size
    return [p for p in parts if p]


def copy_entry(src: zipfile.ZipFile, dst: zipfile.ZipFile, info: zipfile.ZipInfo):
    """Stream one entry from src to dst without loading it fully into memory."""
    new_info = zipfile.ZipInfo(info.filename, date_time=info.date_time)
    new_info.external_attr = info.external_attr
    # Images are already compressed, so store them; deflate anything else.
    is_image = Path(info.filename).suffix.lower() in IMAGE_EXTS
    new_info.compress_type = zipfile.ZIP_STORED if is_image else zipfile.ZIP_DEFLATED
    new_info.file_size = info.file_size
    with src.open(info) as fin, dst.open(new_info, "w", force_zip64=True) as fout:
        while True:
            buf = fin.read(CHUNK)
            if not buf:
                break
            fout.write(buf)


def main():
    ap = argparse.ArgumentParser(description="Split a CBZ into smaller CBZ files.")
    ap.add_argument("cbz", type=Path, help="Input .cbz file")
    group = ap.add_mutually_exclusive_group()
    group.add_argument("--size", type=float, default=600,
                       help="Target size per part in MB (default: 600)")
    group.add_argument("--parts", type=int,
                       help="Split into this many roughly equal parts instead")
    ap.add_argument("-o", "--outdir", type=Path,
                    help="Output folder (default: same folder as input)")
    args = ap.parse_args()

    src_path: Path = args.cbz
    if not src_path.is_file():
        sys.exit(f"File not found: {src_path}")

    outdir = args.outdir or src_path.parent
    outdir.mkdir(parents=True, exist_ok=True)

    with zipfile.ZipFile(src_path) as src:
        all_entries = [i for i in src.infolist() if not i.is_dir()]
        metadata = [i for i in all_entries if Path(i.filename).name.lower() in METADATA_NAMES]
        pages = sorted((i for i in all_entries if i not in metadata),
                       key=lambda i: natural_key(i.filename))

        if not pages:
            sys.exit("No pages found in the archive.")

        total = sum(i.compress_size for i in pages)
        if args.parts:
            parts = plan_n_parts(pages, args.parts)
        else:
            parts = plan_parts(pages, int(args.size * 1024 * 1024))
        n = len(parts)
        if n == 1:
            print("Archive is already under the target size; nothing to split.")
            return

        width = max(2, len(str(n)))
        stem = src_path.stem
        print(f"{src_path.name}: {len(pages)} pages, {total / 1024**2:.0f} MB -> {n} parts")

        for idx, part in enumerate(parts, 1):
            out_path = outdir / f"{stem} - Part {idx:0{width}d}.cbz"
            with zipfile.ZipFile(out_path, "w", allowZip64=True) as dst:
                for info in metadata:
                    copy_entry(src, dst, info)
                for info in part:
                    copy_entry(src, dst, info)
            size_mb = out_path.stat().st_size / 1024**2
            first = Path(part[0].filename).name
            last = Path(part[-1].filename).name
            print(f"  [{idx}/{n}] {out_path.name}  {size_mb:.0f} MB  "
                  f"({len(part)} pages: {first} .. {last})")

    print("Done.")


if __name__ == "__main__":
    main()
