"""Populate three non-destructive storyboard setup references per concept."""

from __future__ import annotations

import csv
import hashlib
import json
import shutil
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1] / "content" / "speech"
PLAN = json.loads((ROOT / "plan" / "content-plan.json").read_text(encoding="utf-8"))
PURPOSES = ["identification", "meaning", "generalisation_probe"]


def concept_path(c: dict) -> Path:
    return ROOT / "concepts" / Path(*c["category"].split(".")) / c["key"]


def digest(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


created = 0
for concept in PLAN["concepts"]:
    base = concept_path(concept)
    image_dir = base / "images"
    video_dir = base / "videos"
    with (image_dir / "assets.csv").open(encoding="utf-8", newline="") as stream:
        images = {row["purpose"]: row for row in csv.DictReader(stream)}
    plan = json.loads((video_dir / "video-generation-plan.json").read_text(encoding="utf-8"))
    records = []
    for index, (video, image_purpose) in enumerate(zip(plan["videos"], PURPOSES), 1):
        source_row = images[image_purpose]
        source = image_dir / source_row["filename"]
        destination = video_dir / f"{video['video_key']}_setup_01.png"
        already_present = destination.exists()
        if not already_present:
            shutil.copy2(source, destination)
            created += 1
        is_reused_reference = digest(destination) == digest(source)
        records.append({
            "video_key": video["video_key"],
            "video_purpose": video["purpose"],
            "setup_key": f"{video['video_key']}_setup_01",
            "filename": destination.name,
            "source_reference": f"../images/{source.name}",
            "source_asset_key": source_row["asset_key"],
            "creation_mode": "reviewed-concept-image-reused-as-storyboard-reference" if is_reused_reference else "purpose-built-generated-frame",
            "semantic_setup": video["setup"],
            "video_generation_prompt": video["generation_prompt"],
            "width_height_policy": "reference composition; final video renders landscape 16:9",
            "checksum": digest(destination),
            "status": "internal_storyboard_review",
            "review_required": ["SLP", "accessibility", "cultural", "rights", "video continuity"],
        })
    manifest = {
        "schema_version": 1,
        "concept_key": concept["key"],
        "expected_setups": 3,
        "generated_or_reused_setups": len(records),
        "setups": records,
    }
    (video_dir / "storyboard-setups.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

print(f"Storyboard setups ready: {len(PLAN['concepts']) * 3}; {created} missing image files created")
