"""Adapters from Retention Studio mechanism explainers into production shot plans."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from autoshorts.script_drafts import _slug

BEAT_TO_PURPOSE = {
    "pattern_interrupt": "pattern_interrupt",
    "problem": "problem",
    "mechanism": "mechanism_reveal",
    "twist": "twist",
    "follow_trigger": "follow_trigger",
}

BEAT_TO_ASSET_TYPE = {
    "pattern_interrupt": "cinematic_ai_video",
    "problem": "cinematic_ai_video",
    "mechanism": "mechanism_animation",
    "twist": "mechanism_animation",
    "follow_trigger": "kinetic_text_overlay",
}


def _plan_id(explainer: dict[str, Any]) -> str:
    return f"{_slug(explainer['pillar'])}-{_slug(explainer['title'])}"


def _overlay_text(voiceover: str, limit: int = 72) -> str:
    cleaned = " ".join(voiceover.split())
    if len(cleaned) <= limit:
        return cleaned
    truncated = cleaned[: limit - 1].rsplit(" ", 1)[0].rstrip(".,;:")
    while truncated.split() and truncated.split()[-1].lower() in {"und", "oder", "mit", "durch", "von", "der", "die", "das"}:
        truncated = " ".join(truncated.split()[:-1]).rstrip(".,;:")
    return f"{truncated}…"


def _scene_from_beat(index: int, beat: dict[str, Any]) -> dict[str, Any]:
    beat_name = beat["beat"]
    return {
        "scene": index,
        "purpose": BEAT_TO_PURPOSE[beat_name],
        "start": beat["start"],
        "end": beat["end"],
        "asset_type": BEAT_TO_ASSET_TYPE[beat_name],
        "on_screen_text": _overlay_text(beat["voiceover"]),
        "voiceover": beat["voiceover"],
        "visual_direction": beat["visual"],
        "visual_motion": beat["visual_motion"],
        "sound_cue": beat["sound_cue"],
        "retention_goal": _retention_goal(beat_name),
    }


def _retention_goal(beat_name: str) -> str:
    goals = {
        "pattern_interrupt": "Open a visual loop immediately; make the viewer need the hidden explanation.",
        "problem": "Make the surface-level interpretation feel incomplete.",
        "mechanism": "Reveal the invisible system through moving layers, not narration alone.",
        "twist": "Reframe the obvious cause into the real cause.",
        "follow_trigger": "Promise the next hidden system without a generic like/follow plea.",
    }
    return goals[beat_name]


def build_mechanism_shot_plan(explainer: dict[str, Any]) -> dict[str, Any]:
    """Convert a Retention Studio mechanism explainer into a motion-led shot plan."""
    scenes = [_scene_from_beat(index, beat) for index, beat in enumerate(explainer["beats"], start=1)]
    caption_beats = [
        {"start": int(beat["start"]), "text": beat["voiceover"]}
        for beat in explainer["beats"]
    ]
    return {
        "id": _plan_id(explainer),
        "series": explainer["series"],
        "title": explainer["title"],
        "pillar": explainer["pillar"],
        "estimated_seconds": int(explainer["target_seconds"]),
        "caption_beats": caption_beats,
        "scenes": scenes,
        "final_render_intent": {
            "static_card_limit": 0,
            "visual_change_every_seconds": 2,
            "primary_style": "mechanism_reveal_motion_explainer",
            "captions": "large kinetic overlays; voiceover carries detail; no paragraph cards",
        },
    }


def format_mechanism_shot_plan(plan: dict[str, Any]) -> str:
    scene_blocks = []
    for scene in plan["scenes"]:
        scene_blocks.append(
            f"### Scene {scene['scene']} — {scene['purpose']}\n\n"
            f"- Timing: {scene['start']}s–{scene['end']}s\n"
            f"- Asset type: {scene['asset_type']}\n"
            f"- On-screen text: {scene['on_screen_text']}\n"
            f"- Voiceover: {scene['voiceover']}\n"
            f"- Visual direction: {scene['visual_direction']}\n"
            f"- Visual motion: {scene['visual_motion']}\n"
            f"- Sound cue: {scene['sound_cue']}\n"
            f"- Retention goal: {scene['retention_goal']}"
        )
    scenes = "\n\n".join(scene_blocks)
    beats = "\n".join(f"- {beat['start']:02d}s: {beat['text']}" for beat in plan["caption_beats"])
    intent = plan["final_render_intent"]
    return f"""# {plan['title']}

- ID: `{plan['id']}`
- Series: {plan['series']}
- Pillar: `{plan['pillar']}`
- Estimated duration: {plan['estimated_seconds']}s

## Mechanism shot plan

{scenes}

## Caption beats

{beats}

## Final render intent

- Static card limit: {intent['static_card_limit']}
- Visual change every seconds: {intent['visual_change_every_seconds']}
- Primary style: {intent['primary_style']}
- Captions: {intent['captions']}
"""


def write_mechanism_shot_plans(explainers: list[dict[str, Any]], output_dir: Path) -> list[Path]:
    """Write mechanism shot plans as Markdown files."""
    output_dir.mkdir(parents=True, exist_ok=True)
    paths: list[Path] = []
    for explainer in explainers:
        plan = build_mechanism_shot_plan(explainer)
        path = output_dir / f"{plan['id']}.md"
        path.write_text(format_mechanism_shot_plan(plan), encoding="utf-8")
        paths.append(path)
    return paths
