"""Keyframe request packages for AI image generation.

The package is intended for ChatGPT Pro or any image generator: create clean
start images first, then feed those into Wan2.2 I2V jobs. The renderer adds all
truth-sensitive captions, numbers, arrows and labels later.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any


FPS_POLICY = {
    "generation_fps": 12,
    "generation_frames": 61,
    "generation_duration_seconds": 5.08,
    "final_delivery_fps": 24,
    "interpolation": "renderer_or_ffmpeg_optical_flow_to_24fps",
    "reason": "12fps/61f is a smoother local Wan2.2 generation target on 16GB VRAM; final Shorts should be delivered at 24fps after interpolation/compositing.",
}


def _target_path(keyframe_root: Path, video_id: str, scene_id: str) -> Path:
    return keyframe_root / video_id / f"{scene_id}.png"


def _checklist() -> list[str]:
    return [
        "subject clearly visible in the first frame",
        "full object visible with clean silhouette",
        "bright balanced exposure, not dark cinematic mush",
        "no readable text/logos/license plates",
        "enough negative space in upper and lower thirds for captions",
        "photorealistic texture, no cartoon or fantasy styling",
        "movement implied by pose/composition where possible",
    ]


def build_keyframe_requests(prompt_plan: dict[str, Any], keyframe_root: Path) -> dict[str, Any]:
    """Build a generator-ready keyframe request package from an I2V prompt plan."""
    video = prompt_plan["video"]
    requests: list[dict[str, Any]] = []
    for scene in prompt_plan["scenes"]:
        comfy = scene["comfyui"]
        requests.append(
            {
                "scene_id": scene["scene_id"],
                "purpose": scene["purpose"],
                "target_path": str(_target_path(keyframe_root, video["id"], scene["scene_id"])),
                "generator": "ChatGPT Pro image generation or equivalent photorealistic image model",
                "generator_prompt": scene["keyframe_prompt"],
                "negative_requirements": scene["negative_prompt"],
                "required_format": {
                    "width": int(comfy["resolution"]["width"]),
                    "height": int(comfy["resolution"]["height"]),
                    "format": "png",
                },
                "acceptance_checklist": _checklist(),
                "downstream_i2v_prompt": scene["i2v_motion_prompt"],
            }
        )
    return {
        "schema_version": "keyframe_requests.v1",
        "video": video,
        "style_profile": prompt_plan["style_profile"],
        "workflow": "ChatGPT Pro keyframe -> Wan2.2 I2V -> deterministic renderer overlays",
        "fps_policy": FPS_POLICY,
        "requests": requests,
    }


def write_keyframe_package(prompt_plan: dict[str, Any], output_file: Path, keyframe_root: Path) -> Path:
    """Write a keyframe request package as JSON."""
    output_file.parent.mkdir(parents=True, exist_ok=True)
    package = build_keyframe_requests(prompt_plan, keyframe_root)
    output_file.write_text(json.dumps(package, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    return output_file
