"""Script draft and Telegram review formatting helpers."""

from __future__ import annotations

import re
from pathlib import Path
from typing import Any

from autoshorts.retention import score_idea_retention


def _slug(value: str) -> str:
    slug = re.sub(r"[^a-zA-Z0-9]+", "-", value.lower()).strip("-")
    return slug or "draft"


def _hashtags_for_pillar(pillar: str) -> list[str]:
    defaults = {
        "life_optimization": ["#focus", "#selfimprovement", "#lifesystems", "#mindset"],
        "ai_life_systems": ["#ai", "#productivity", "#prompts", "#lifesystems"],
        "faithtok": ["#faithtok", "#christian", "#prayer", "#discipline"],
    }
    return defaults.get(pillar, ["#shorts", "#growth"])


def _allocate_sections(duration_seconds: int) -> list[tuple[str, int]]:
    """Allocate simple timed sections that sum exactly to the target duration."""
    hook = min(3, max(2, duration_seconds // 10))
    cta = min(5, max(3, duration_seconds // 12))
    setup = max(5, int(duration_seconds * 0.24))
    value = max(8, duration_seconds - hook - cta - setup)
    total = hook + setup + value + cta
    value += duration_seconds - total
    return [("Hook", hook), ("Setup", setup), ("Core Value", value), ("CTA", cta)]


def build_script_draft(idea: dict[str, Any]) -> dict[str, Any]:
    """Build a deterministic first script draft from a curated testbatch idea."""
    duration = int(idea["duration_seconds"])
    allocations = _allocate_sections(duration)
    outline = idea["script_outline"].strip()
    hook = idea["hook"].strip()
    cta = idea["cta"].strip()

    sections = [
        {"label": "Hook", "seconds": allocations[0][1], "text": hook},
        {
            "label": "Setup",
            "seconds": allocations[1][1],
            "text": _setup_line(idea),
        },
        {
            "label": "Core Value",
            "seconds": allocations[2][1],
            "text": outline,
        },
        {"label": "CTA", "seconds": allocations[3][1], "text": cta},
    ]

    retention = score_idea_retention(idea)

    return {
        "id": idea["id"],
        "pillar": idea["pillar"],
        "title": idea["title"],
        "duration_seconds": duration,
        "platform_target": idea["platform_target"],
        "platform_note": "TikTok Rewards Candidate" if duration >= 60 else "Growth Short",
        "hook": hook,
        "sections": sections,
        "visual_concept": idea["visual_concept"],
        "caption": idea["caption"],
        "cta": cta,
        "hashtags": _hashtags_for_pillar(idea["pillar"]),
        "quality_score": int(idea["quality_score"]),
        "retention_score": retention["score"],
        "retention_signals": retention["signals"],
        "retention_risks": retention["risks"],
        "risk_notes": idea.get("risk_notes", ""),
    }


def _setup_line(idea: dict[str, Any]) -> str:
    pillar = idea["pillar"]
    if pillar == "faithtok":
        return "A quiet, honest moment for people who feel spiritually tired but still want to return to God."
    if pillar == "ai_life_systems":
        return "The point is not hype. The point is a simple system where the human stays in charge."
    if pillar == "attention_design":
        return "This is not a willpower lecture. It is attention design: change the default before the feed chooses for you."
    return "This is not another motivation trick. It is a small environmental system you can test today."


def format_telegram_review(draft: dict[str, Any]) -> str:
    """Format a draft for Telegram approval review."""
    platforms = ", ".join(draft["platform_target"])
    hashtags = " ".join(draft["hashtags"])
    sections = "\n".join(
        f"- **{section['label']}** ({section['seconds']}s): {section['text']}"
        for section in draft["sections"]
    )
    return f"""## AutoShortsBot Review

**ID:** `{draft['id']}`
**Pillar:** `{draft['pillar']}`
**Title:** {draft['title']}
**Duration:** {draft['duration_seconds']}s — {draft['platform_note']}
**Platforms:** {platforms}
**Quality Score:** {draft['quality_score']}/10
**Retention Score:** {draft['retention_score']}/10
**Retention Signals:** {', '.join(draft['retention_signals']) or 'none'}
**Retention Risks:** {', '.join(draft['retention_risks']) or 'none'}

**Hook:** {draft['hook']}

**Script Draft:**
{sections}

**Visual Concept:** {draft['visual_concept']}

**Caption:** {draft['caption']}
**Hashtags:** {hashtags}

**Policy/Risk Notes:** {draft['risk_notes'] or 'Keine besonderen Risiken.'}

**Approval commands:**
- `Freigabe alle`
- `Freigabe YouTube`
- `Freigabe TikTok`
- `Freigabe Instagram`
- `Ablehnen`
- `Ändern: <Wunsch>`
"""


def write_review_drafts(batch: dict[str, Any], output_dir: Path) -> list[Path]:
    """Write one Telegram-ready Markdown review file per idea."""
    output_dir.mkdir(parents=True, exist_ok=True)
    written: list[Path] = []
    for idea in batch.get("ideas", []):
        draft = build_script_draft(idea)
        path = output_dir / f"{draft['id']}-{_slug(draft['title'])}.md"
        path.write_text(format_telegram_review(draft), encoding="utf-8")
        written.append(path)
    return written
