"""Final short-form voiceover scripts for TrueTrace review renders."""

from __future__ import annotations

from dataclasses import dataclass

from autoshorts.content.script_draft import ScriptDraft, validate_script_draft
from autoshorts.ideas.candidate import ValidationResult


_GENERIC_FILLER = (
    "in this video",
    "unlock your full potential",
    "game changer",
    "you won't believe",
)


@dataclass(frozen=True)
class FinalVoiceoverScript:
    candidate_id: str
    text: str
    language: str
    voice: str
    target_duration_seconds: int
    side_effects: tuple[str, ...] = ()
    external_calls: tuple[str, ...] = ()


_SCRIPTS: dict[str, tuple[str, int]] = {
    "truetrace-ai-automation-quiet-rot-38s": (
        "Your AI automation works perfectly in the demo. Then one weird email arrives. "
        "The name is missing. The format is different. The request is unclear. "
        "And suddenly the automation does the wrong thing confidently. "
        "That is not an AI problem. That is a workflow problem. "
        "Before you automate anything, decide three things. What should go through? "
        "What should be reviewed? And what should stop? If your AI does not know what to do with weird inputs, "
        "it will break the moment real life shows up.",
        37,
    ),
    "truetrace-prompt-vs-system-workflow-breaks-35s": (
        "A smart prompt can still build a fragile workflow. The prompt is only one part. "
        "A system needs an input boundary, an output standard, a review step, and an action boundary. "
        "Without those, the same prompt behaves differently every week. Do not ask for a better prompt first. "
        "Ask what the workflow must refuse, review, and repeat.",
        23,
    ),
    "truetrace-ai-notes-equal-importance-34s": (
        "AI notes fail when everything looks equally important. A pretty summary is not a decision system. "
        "Separate facts from decisions, risks, open questions, and next actions. "
        "Now the note tells you what changed, what matters, and what needs a human. "
        "Do not ask AI for more notes. Ask it for decision structure.",
        22,
    ),
}


def build_truetrace_final_voiceover(candidate_id: str) -> FinalVoiceoverScript:
    if candidate_id not in _SCRIPTS:
        raise ValueError(f"unknown TrueTrace candidate id: {candidate_id}")
    text, duration = _SCRIPTS[candidate_id]
    script = FinalVoiceoverScript(
        candidate_id=candidate_id,
        text=text,
        language="en",
        voice="en-GB-RyanNeural",
        target_duration_seconds=duration,
    )
    validation = validate_final_voiceover_script(script)
    if not validation.is_valid:
        raise ValueError("; ".join(validation.errors))
    return script


def build_accessible_script_draft_from_voiceover(voiceover: FinalVoiceoverScript) -> ScriptDraft:
    """Create the render-planning script from the final voiceover so cards/captions match the spoken text."""

    validation = validate_final_voiceover_script(voiceover)
    if not validation.is_valid:
        raise ValueError("; ".join(validation.errors))
    if voiceover.candidate_id != "truetrace-ai-automation-quiet-rot-38s":
        raise ValueError("accessible script draft is only defined for the weird-email pilot")

    draft = ScriptDraft(
        brief_id=voiceover.candidate_id,
        title="Your AI automation works in the demo. Then real life shows up.",
        hook="Your AI automation works perfectly in the demo. Then one weird email arrives.",
        script_outline=voiceover.text,
        retention_beats=(
            "The name is missing. The format is different. The request is unclear.",
            "Suddenly the automation does the wrong thing confidently.",
            "That is not an AI problem. That is a workflow problem.",
            "Decide what goes through, what gets reviewed, and what must stop.",
        ),
        visual_concept=(
            "A clean demo inbox is interrupted by one weird email, then splits into three simple paths: "
            "go through, review, or stop."
        ),
        caption="Your AI automation works perfectly in the demo. Then one weird email arrives.",
        cta="Plan for the weird input before you automate the normal one.",
        estimated_duration_seconds=voiceover.target_duration_seconds,
    )
    draft_validation = validate_script_draft(draft)
    if not draft_validation.is_valid:
        raise ValueError("; ".join(draft_validation.errors))
    return draft


def validate_final_voiceover_script(script: FinalVoiceoverScript) -> ValidationResult:
    errors: list[str] = []
    if not script.candidate_id.strip():
        errors.append("candidate_id is required")
    if not script.text.strip():
        errors.append("text is required")
    if script.language != "en":
        errors.append("final voiceover language must be en")
    if not script.voice.strip():
        errors.append("voice is required")
    if not (15 <= script.target_duration_seconds <= 45):
        errors.append("target_duration_seconds must be between 15 and 45")
    if any(phrase in script.text.casefold() for phrase in _GENERIC_FILLER):
        errors.append("voiceover contains generic intro/filler language")
    if len(script.text.split()) > 90:
        errors.append("voiceover must stay under 90 words")
    if script.side_effects:
        errors.append("voiceover script must not have side effects")
    if script.external_calls:
        errors.append("voiceover script must not have external calls")
    return ValidationResult(is_valid=not errors, errors=tuple(errors))
