"""Retention Studio strategy for mechanism-explainer Shorts.

This module captures the strategic shift from generic AI-video output to a
semi-automatic retention studio: format mining, idea scoring, mechanism-reveal
scripts, motion-led visuals, and human quality gates.
"""

from __future__ import annotations

from typing import Any

PILOT_IDEAS: list[dict[str, Any]] = [
    {
        "title": "Warum ein billiges Auto teuer sein kann",
        "pillar": "hidden_money_systems",
        "hook": "Dieser Occasion-Käufer denkt, er spart 4'000 Franken.",
        "mechanism": "Röntgenblick durch Preis, Reparaturrisiko, Standtage, Händler-Marge und Liquidität.",
        "twist": "Der teuerste Fehler ist nicht der Kaufpreis, sondern der Zeitpunkt.",
        "visual_mechanism": "3D car x-ray with price tag layers and risk meters",
        "surprise": 9,
        "data_basis": 8,
        "comment_potential": 8,
        "series_potential": 9,
        "monetization_potential": 10,
        "production_effort": 6,
    },
    {
        "title": "Warum 0%-Finanzierung nicht kostenlos ist",
        "pillar": "hidden_money_systems",
        "hook": "0 Prozent klingt gratis. Genau deshalb funktioniert es.",
        "mechanism": "Cash price, margin, fees, lock-in and opportunity cost split into layers.",
        "twist": "Die Zinsen verschwinden nicht. Sie verstecken sich nur im System.",
        "visual_mechanism": "contract transforms into hidden cost layers",
        "surprise": 8,
        "data_basis": 7,
        "comment_potential": 8,
        "series_potential": 9,
        "monetization_potential": 10,
        "production_effort": 5,
    },
    {
        "title": "Warum KI-Agenten ohne Regeln gefährlich werden",
        "pillar": "ai_agents_explained",
        "hook": "Dieser Agent wirkt produktiv. Bis er ohne Kontrolle Geld verbrennt.",
        "mechanism": "Goal, tool access, missing approval gates, runaway loops and audit trail visualized as a circuit.",
        "twist": "Der Fehler ist nicht Intelligenz. Der Fehler ist fehlende Begrenzung.",
        "visual_mechanism": "agent control loop with approval gate and red runaway path",
        "surprise": 8,
        "data_basis": 8,
        "comment_potential": 9,
        "series_potential": 10,
        "monetization_potential": 10,
        "production_effort": 5,
    },
    {
        "title": "Der Unterschied zwischen Chatbot und echtem Agenten",
        "pillar": "ai_agents_explained",
        "hook": "Ein Chatbot antwortet. Ein Agent verändert Dinge.",
        "mechanism": "Intent, tools, memory, approvals and execution are revealed as separate layers.",
        "twist": "Autonomie beginnt nicht beim Modell, sondern beim Zugriff.",
        "visual_mechanism": "split-screen chatbot bubble vs agent toolchain",
        "surprise": 7,
        "data_basis": 8,
        "comment_potential": 8,
        "series_potential": 10,
        "monetization_potential": 9,
        "production_effort": 4,
    },
    {
        "title": "Warum ein Bauprojekt fast nie beim ersten Preis bleibt",
        "pillar": "swiss_systems_explained",
        "hook": "Dieser Baukredit sieht fix aus. Dann beginnt die Schweiz.",
        "mechanism": "Permits, objections, procurement, inflation, scope creep and political process stack over time.",
        "twist": "Die Überraschung ist nicht der Mehrpreis. Es ist die Anzahl unsichtbarer Schleifen.",
        "visual_mechanism": "construction budget timeline with process gates and cost bubbles",
        "surprise": 8,
        "data_basis": 8,
        "comment_potential": 7,
        "series_potential": 9,
        "monetization_potential": 7,
        "production_effort": 7,
    },
    {
        "title": "Wie ein Einwohnerrat wirklich entscheidet",
        "pillar": "swiss_systems_explained",
        "hook": "Das sieht wie eine Abstimmung aus. Eigentlich ist es ein Filtersystem.",
        "mechanism": "Motion, committee, budget, party positions, amendments and final vote visualized as a flow.",
        "twist": "Die Entscheidung fällt oft, bevor die Schlussabstimmung beginnt.",
        "visual_mechanism": "council chamber turns into decision flowchart",
        "surprise": 7,
        "data_basis": 8,
        "comment_potential": 7,
        "series_potential": 8,
        "monetization_potential": 6,
        "production_effort": 6,
    },
    {
        "title": "Warum dein Gehirn schlechte Deals schönrechnet",
        "pillar": "dangerous_thinking_errors",
        "hook": "Dein Gehirn merkt diesen schlechten Deal. Dann verteidigt es ihn.",
        "mechanism": "Sunk cost, confirmation bias and loss aversion appear as competing brain layers.",
        "twist": "Du kaufst nicht den Deal. Du kaufst die Rechtfertigung.",
        "visual_mechanism": "brain courtroom where biases argue over a bad deal",
        "surprise": 9,
        "data_basis": 7,
        "comment_potential": 9,
        "series_potential": 10,
        "monetization_potential": 8,
        "production_effort": 5,
    },
    {
        "title": "Warum du Verlusten hinterherrennst",
        "pillar": "dangerous_thinking_errors",
        "hook": "Der Verlust ist vorbei. Trotzdem zahlst du weiter.",
        "mechanism": "Loss aversion, sunk cost and identity protection visualized as a trap door.",
        "twist": "Du rettest nicht dein Geld. Du rettest dein altes Ich.",
        "visual_mechanism": "money trail into trap with brain pulling it back",
        "surprise": 8,
        "data_basis": 7,
        "comment_potential": 8,
        "series_potential": 9,
        "monetization_potential": 8,
        "production_effort": 5,
    },
    {
        "title": "Warum Shorts dich nicht wegen dem Inhalt halten",
        "pillar": "hidden_attention_systems",
        "hook": "Du bleibst nicht wegen dem Thema. Du bleibst wegen der offenen Schleife.",
        "mechanism": "Hook, open loop, pattern interrupt, payoff delay and reward pulse shown as timeline layers.",
        "twist": "Retention ist oft Architektur, nicht Interesse.",
        "visual_mechanism": "shorts timeline with dopamine gates and loop markers",
        "surprise": 9,
        "data_basis": 8,
        "comment_potential": 9,
        "series_potential": 10,
        "monetization_potential": 8,
        "production_effort": 5,
    },
    {
        "title": "Warum Banken Gebühren verstecken können, ohne sie zu verstecken",
        "pillar": "hidden_money_systems",
        "hook": "Diese Gebühr ist sichtbar. Genau deshalb übersiehst du sie.",
        "mechanism": "Statement line items, percentage framing, monthly smoothing and comparison blindness.",
        "twist": "Das Versteck ist nicht Geheimhaltung. Es ist Normalisierung.",
        "visual_mechanism": "bank statement zooms into visible-but-ignored fee layers",
        "surprise": 8,
        "data_basis": 7,
        "comment_potential": 8,
        "series_potential": 9,
        "monetization_potential": 9,
        "production_effort": 5,
    },
]


def build_retention_studio_strategy() -> dict[str, Any]:
    """Return the strategic operating model for the channel."""
    return {
        "positioning": "Hidden Money & AI Systems",
        "series": "Unsichtbare Systeme in 30 Sekunden",
        "claim": "Wir zeigen Dinge, die dich Geld, Zeit oder Kontrolle kosten – bevor du sie bemerkst.",
        "operating_model": "semi_automatic_retention_studio",
        "not_a": ["ki_avatar_news", "static_ai_slideshow", "reused_content_clone"],
        "core_formula": [
            "0.0-1.5s pattern interrupt",
            "1.5-5s problem",
            "5-18s mechanism reveal",
            "18-28s twist",
            "28-35s follow trigger",
        ],
        "format_taxonomy": [
            "mechanism_reveal",
            "mistake_breakdown",
            "hidden_cost",
            "before_after",
            "myth_vs_reality",
            "mini_simulation",
            "nobody_notices_this",
        ],
        "content_pillars": [
            "hidden_money_systems",
            "auto_trade_mechanics",
            "ai_agents_explained",
            "swiss_systems_explained",
            "dangerous_thinking_errors",
        ],
        "quality_gates": {
            "static_card_limit": 0,
            "first_two_seconds_must_open_loop": True,
            "visual_change_every_seconds": 2,
            "human_review_percent": 20,
            "reused_content_allowed": False,
            "synthetic_media_disclosure_required_when_realistic": True,
        },
        "metrics": [
            "retention_1s",
            "retention_3s",
            "average_view_duration",
            "rewatches",
            "comments_per_1000_views",
            "follows_per_1000_views",
        ],
    }


def score_idea(idea: dict[str, Any]) -> dict[str, Any]:
    """Score an idea for production priority."""
    weights = {
        "surprise": 1.6,
        "data_basis": 1.2,
        "comment_potential": 1.2,
        "series_potential": 1.4,
        "monetization_potential": 1.4,
    }
    weighted = sum(float(idea.get(key, 0)) * weight for key, weight in weights.items())
    visual_bonus = 12 if _has_specific_visual_mechanism(str(idea.get("visual_mechanism", ""))) else 0
    effort_penalty = max(0, float(idea.get("production_effort", 5)) - 5) * 2
    total = round(min(100, weighted / sum(weights.values()) * 8.8 + visual_bonus - effort_penalty))
    if total >= 80:
        decision = "produce"
    elif total >= 65:
        decision = "develop"
    else:
        decision = "reject"
    return {"total": total, "decision": decision}


def _has_specific_visual_mechanism(visual_mechanism: str) -> bool:
    generic_terms = {"generic montage", "talking avatar", "static image", "slideshow"}
    if visual_mechanism.lower().strip() in generic_terms:
        return False
    return any(
        token in visual_mechanism.lower()
        for token in ["x-ray", "röntgen", "layer", "simulation", "timeline", "flow", "split", "3d", "circuit"]
    )


def build_mechanism_explainer(idea: dict[str, Any]) -> dict[str, Any]:
    """Build a shot-by-shot mechanism explainer skeleton from a scored idea."""
    follow_trigger = "Morgen zeige ich das nächste versteckte System, bevor es dich Geld kostet."
    return {
        "series": "Unsichtbare Systeme in 30 Sekunden",
        "title": idea["title"],
        "pillar": idea["pillar"],
        "target_seconds": 34,
        "follow_trigger": follow_trigger,
        "beats": [
            {
                "beat": "pattern_interrupt",
                "start": 0.0,
                "end": 1.4,
                "voiceover": idea["hook"],
                "visual": f"{idea['visual_mechanism']} freezes mid-action with warning signal.",
                "visual_motion": "hard zoom, freeze-frame, red signal pulse",
                "sound_cue": "bass hit + camera snap",
            },
            {
                "beat": "problem",
                "start": 1.4,
                "end": 5.0,
                "voiceover": "Das sieht harmlos aus, bis du den Mechanismus dahinter siehst.",
                "visual": "surface layer peels away to reveal the hidden system underneath.",
                "visual_motion": "layer peel + parallax push",
                "sound_cue": "whoosh + low tension tick",
            },
            {
                "beat": "mechanism",
                "start": 5.0,
                "end": 18.0,
                "voiceover": idea["mechanism"],
                "visual": idea["visual_mechanism"],
                "visual_motion": "sequential layer reveal every 1-2 seconds",
                "sound_cue": "clicks per revealed layer",
            },
            {
                "beat": "twist",
                "start": 18.0,
                "end": 28.0,
                "voiceover": idea["twist"],
                "visual": "camera snaps from obvious cause to real cause; wrong layer fades out.",
                "visual_motion": "snap zoom + wrong answer collapses",
                "sound_cue": "drop + silence beat",
            },
            {
                "beat": "follow_trigger",
                "start": 28.0,
                "end": 34.0,
                "voiceover": follow_trigger,
                "visual": "series tag appears over a clean animated system map.",
                "visual_motion": "map draws itself, final node glows",
                "sound_cue": "resolve hit + soft riser",
            },
        ],
    }
