from pathlib import Path

from autoshorts.growth_plan import load_testbatch
from autoshorts.shot_planner import build_shot_plan, write_shot_plans
from autoshorts.voiceover_finalizer import finalize_voiceover


def _final_script(script_id: str):
    batch = load_testbatch(Path("data/drafts/testbatch_002.json"))
    idea = next(item for item in batch["ideas"] if item["id"] == script_id)
    return finalize_voiceover(idea)


def test_build_shot_plan_creates_five_retention_scenes_for_ai_script():
    final = _final_script("ai-004")

    plan = build_shot_plan(final)

    assert plan["id"] == "ai-004"
    assert plan["title"] == final["title"]
    assert len(plan["scenes"]) == 5
    assert [scene["purpose"] for scene in plan["scenes"]] == [
        "first_frame_hook",
        "pattern_interrupt",
        "core_explanation",
        "screen_or_card_visual",
        "cta",
    ]
    assert plan["scenes"][0]["start"] == 0
    assert plan["scenes"][0]["asset_type"] == "kinetic_text"
    assert "Ask it to argue" in plan["scenes"][0]["on_screen_text"]
    assert any(scene["asset_type"] == "screen_recording" for scene in plan["scenes"])
    assert all(scene["retention_goal"] for scene in plan["scenes"])


def test_build_shot_plan_uses_card_animation_for_attention_design():
    final = _final_script("attention-002")

    plan = build_shot_plan(final)

    asset_types = [scene["asset_type"] for scene in plan["scenes"]]
    assert "card_animation" in asset_types
    assert "stock_broll" in asset_types
    assert plan["scenes"][-1]["purpose"] == "cta"
    assert "home screen" in plan["scenes"][-1]["visual_direction"].lower()


def test_write_shot_plans_outputs_selected_markdown_files(tmp_path):
    finals = [_final_script("ai-004"), _final_script("ai-005"), _final_script("attention-002")]

    paths = write_shot_plans(finals, tmp_path)

    assert len(paths) == 3
    assert all(path.suffix == ".md" for path in paths)
    text = paths[0].read_text(encoding="utf-8")
    assert "## Shot plan" in text
    assert "first_frame_hook" in text
    assert "Asset type" in text
    assert "Caption beats" in text
