#!/usr/bin/env python3
"""Build a family-chat pack from files, a directory, or a ZIP of image assets."""

import argparse
import base64
import json
import io
import re
import unicodedata
from pathlib import Path
import zipfile

EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".apng"}
MAX_ITEM = 8 * 1024 * 1024
MAX_TOTAL = 24 * 1024 * 1024


def directory_images(root):
    for path in sorted(root.iterdir()):
        if path.is_file() and path.suffix.lower() in EXTENSIONS:
            yield path.stem, path.stat().st_size, path.read_bytes


def pack_images(paths):
    for path in paths:
        if path.is_dir():
            yield from directory_images(path)
        elif path.suffix.lower() in EXTENSIONS:
            yield path.stem, path.stat().st_size, path.read_bytes
        elif zipfile.is_zipfile(path):
            with zipfile.ZipFile(path) as archive:
                for member in archive.infolist():
                    name = Path(member.filename)
                    if not member.is_dir() and name.suffix.lower() in EXTENSIONS and not name.stem.startswith("."):
                        if name.stem.lower() in {"tray", "tray_image", "cover", "icon"}:
                            continue
                        yield name.stem, member.file_size, lambda: archive.read(member)
        else:
            raise ValueError(f"Unsupported source: {path}")


def v2_image(content, kind):
    try:
        from PIL import Image, ImageOps, ImageSequence
    except ImportError as error:
        raise ValueError("v2 pack conversion requires Pillow") from error
    with Image.open(io.BytesIO(content)) as source:
        frame_count = getattr(source, "n_frames", 1)
        if not 1 <= frame_count <= 120 or source.width * source.height * frame_count > 100_000_000:
            raise ValueError("Image exceeds the frame or pixel budget")
        if (frame_count > 1) != (kind == "animated"):
            raise ValueError(f"Frame count does not match the {kind} pack type")
        frames, durations = [], []
        for original in ImageSequence.Iterator(source):
            frame = ImageOps.exif_transpose(original).convert("RGBA")
            frame = ImageOps.contain(frame, (512, 512), Image.Resampling.LANCZOS)
            canvas = Image.new("RGBA", (512, 512))
            canvas.alpha_composite(frame, ((512 - frame.width) // 2, (512 - frame.height) // 2))
            frames.append(canvas)
            durations.append(max(40, min(1000, int(original.info.get("duration", 100)))))
        output = io.BytesIO()
        if kind == "animated":
            frames[0].save(output, format="PNG", save_all=True, append_images=frames[1:],
                           duration=durations, loop=0, disposal=0, blend=0)
            with Image.open(io.BytesIO(output.getvalue())) as encoded:
                if encoded.n_frames < 2:
                    raise ValueError("Animation frames are identical after conversion")
        else:
            frames[0].save(output, format="PNG")
    return output.getvalue(), "image/apng" if kind == "animated" else "image/png"


def item_id(label, original, used):
    slug = unicodedata.normalize("NFKD", label).encode("ascii", "ignore").decode().lower()
    slug = re.sub(r"[^a-z0-9]+", "-", slug).strip("-")[:44]
    if not slug or slug in used:
        import hashlib
        slug = (slug or "sticker") + "-" + hashlib.sha256(original).hexdigest()[:12]
    if slug in used:
        raise ValueError(f"Duplicate sticker: {label}")
    used.add(slug)
    return slug


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--name", required=True)
    parser.add_argument("--out", type=Path, required=True)
    parser.add_argument("--kind", choices=("static", "animated"), help="Produce a typed v2 pack")
    parser.add_argument("--id", help="Stable v2 pack ID")
    parser.add_argument("--publisher", help="v2 author name")
    parser.add_argument("--revision", type=int, default=1)
    parser.add_argument("sources", nargs="+", type=Path)
    args = parser.parse_args()
    stickers = []
    total = 0
    used = set()
    try:
        if args.kind and not (args.id and re.fullmatch(r"[a-z0-9][a-z0-9._-]{0,63}", args.id)
                              and args.publisher and 1 <= len(args.publisher.strip()) <= 40
                              and 1 <= len(args.name.strip()) <= 40 and args.revision >= 1):
            raise ValueError("v2 requires a valid --id, --publisher, --name, and --revision")
        for label, size, read in pack_images(args.sources):
            if len(stickers) == 60 or not 0 < size <= MAX_ITEM or total + size > MAX_TOTAL:
                raise ValueError("Pack exceeds 60 items, 8 MiB per image or 24 MiB total")
            content = read()
            if len(content) != size:
                raise ValueError("Source changed during packaging")
            entry = {"label": label}
            if args.kind:
                identifier = item_id(label, content, used)
                try:
                    content, mime = v2_image(content, args.kind)
                except ValueError as error:
                    raise ValueError(f"{label}: {error}") from error
                if len(content) > MAX_ITEM or total + len(content) > MAX_TOTAL:
                    raise ValueError(f"{label}: converted image exceeds the pack limits")
                entry.update(id=identifier, mime=mime, label=(label.strip() or identifier)[:40])
            total += len(content)
            entry["image"] = base64.b64encode(content).decode("ascii")
            stickers.append(entry)
        if not stickers or not args.name.strip():
            raise ValueError("Supply a name and at least one supported image")
        manifest = {"version": 1, "name": args.name, "stickers": stickers}
        if args.kind:
            manifest.update(version=2, id=args.id, publisher=args.publisher.strip(), name=args.name.strip(),
                            revision=args.revision, type=args.kind, width=512, height=512)
        payload = json.dumps(manifest, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        if len(payload) > 32 * 1024 * 1024:
            raise ValueError("Encoded pack exceeds 32 MiB; split it into two packs")
        args.out.write_bytes(payload)
    except (ValueError, OSError, RuntimeError, zipfile.BadZipFile) as error:
        parser.exit(1, f"{error}\n")
    print(f"{len(stickers)} stickers: {args.out}")


if __name__ == "__main__":
    main()
