#!/usr/bin/env python3
"""Local preparation/export: pip install Pillow. No images leave this process.
Usage: python export.py prepare|export input.png plan.json output.png
The JSON may be an exportPlan, a quote response, or an edit response.
"""
import json
import sys
from PIL import Image, ImageOps


def validate(plan):
    if plan.get("version") != 1:
        raise ValueError("Unsupported export plan")
    for kind in ("target", "canvas", "crop"):
        width, height = plan[kind]["width"], plan[kind]["height"]
        if not isinstance(width, int) or not isinstance(height, int) or not (0 < width <= 16384 and 0 < height <= 16384 and width * height <= 50_000_000):
            raise ValueError("Invalid image dimensions")
    crop, canvas = plan["crop"], plan["canvas"]
    if not all(isinstance(crop[k], int) and crop[k] >= 0 for k in ("x", "y")) or crop["x"] + crop["width"] > canvas["width"] or crop["y"] + crop["height"] > canvas["height"]:
        raise ValueError("Invalid crop")
    if plan["format"] not in ("image/png", "image/jpeg", "image/webp"):
        raise ValueError("Invalid output format")


def run(action, source, plan_file, output):
    with open(plan_file, encoding="utf-8") as handle:
        document = json.load(handle)
    plan = document.get("exportPlan", document)
    validate(plan)
    Image.MAX_IMAGE_PIXELS = 50_000_000
    with Image.open(source) as opened:
        if getattr(opened, "n_frames", 1) != 1:
            raise ValueError("Animated images are not supported")
        profile = opened.info.get("icc_profile")
        image = ImageOps.exif_transpose(opened).convert("RGBA")
    crop, canvas, target = plan["crop"], plan["canvas"], plan["target"]
    if action == "prepare":
        if image.size != (target["width"], target["height"]):
            raise ValueError("Input dimensions do not match the plan")
        resized = image.resize((crop["width"], crop["height"]), Image.Resampling.LANCZOS)
        result = Image.new("RGBA", (canvas["width"], canvas["height"]), "white" if plan["format"] == "image/jpeg" else (0, 0, 0, 0))
        result.paste(resized, (crop["x"], crop["y"]))
        result.save(output, format="PNG")
    elif action == "export":
        if image.size != (canvas["width"], canvas["height"]):
            raise ValueError("Generated image dimensions do not match the plan")
        result = image.crop((crop["x"], crop["y"], crop["x"] + crop["width"], crop["y"] + crop["height"]))
        result = result.resize((target["width"], target["height"]), Image.Resampling.LANCZOS)
        format_name = {"image/png": "PNG", "image/jpeg": "JPEG", "image/webp": "WEBP"}[plan["format"]]
        if format_name == "JPEG":
            flattened = Image.new("RGB", result.size, "white")
            flattened.paste(result, mask=result.getchannel("A"))
            result = flattened
        result.info.clear()
        color = {}
        if (isinstance(profile, bytes) and 128 <= len(profile) <= 4 * 1024 * 1024
                and int.from_bytes(profile[:4], "big") == len(profile)
                and profile[16:20] == b"RGB " and profile[36:40] == b"acsp"):
            color["icc_profile"] = profile
        result.save(output, format=format_name, quality=95, **color)
    else:
        raise ValueError("Action must be prepare or export")


if __name__ == "__main__":
    if len(sys.argv) != 5:
        raise SystemExit(__doc__)
    run(*sys.argv[1:])
