from autoshorts.mechanism_pipeline import (
    build_mechanism_shot_plan,
    write_mechanism_shot_plans,
)
from autoshorts.retention_studio import PILOT_IDEAS, build_mechanism_explainer


def _auto_explainer():
    return build_mechanism_explainer(PILOT_IDEAS[0])


def test_build_mechanism_shot_plan_preserves_retention_beats_and_timing():
    explainer = _auto_explainer()

    plan = build_mechanism_shot_plan(explainer)

    assert plan["id"] == "hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann"
    assert plan["series"] == "Unsichtbare Systeme in 30 Sekunden"
    assert plan["estimated_seconds"] == 34
    assert [scene["purpose"] for scene in plan["scenes"]] == [
        "pattern_interrupt",
        "problem",
        "mechanism_reveal",
        "twist",
        "follow_trigger",
    ]
    assert plan["scenes"][0]["start"] == 0.0
    assert plan["scenes"][0]["end"] <= 1.5
    assert plan["scenes"][2]["asset_type"] == "mechanism_animation"
    assert all(scene["visual_motion"] for scene in plan["scenes"])
    assert all(scene["sound_cue"] for scene in plan["scenes"])


def test_mechanism_shot_plan_uses_motion_led_asset_types_not_static_cards():
    plan = build_mechanism_shot_plan(_auto_explainer())

    asset_types = [scene["asset_type"] for scene in plan["scenes"]]

    assert "static_card" not in asset_types
    assert "cinematic_ai_video" in asset_types
    assert "mechanism_animation" in asset_types
    assert "kinetic_text_overlay" in asset_types
    assert plan["final_render_intent"]["static_card_limit"] == 0
    assert plan["final_render_intent"]["visual_change_every_seconds"] <= 2


def test_mechanism_shot_plan_generates_caption_beats_from_voiceover():
    plan = build_mechanism_shot_plan(_auto_explainer())

    assert len(plan["caption_beats"]) == 5
    assert plan["caption_beats"][0]["start"] == 0
    assert "Occasion" in plan["caption_beats"][0]["text"]
    assert plan["caption_beats"][-1]["start"] == 28
    assert "versteckte" in plan["caption_beats"][-1]["text"].lower()


def test_mechanism_scene_overlay_truncation_marks_open_sentence():
    plan = build_mechanism_shot_plan(_auto_explainer())
    overlay = plan["scenes"][2]["on_screen_text"]

    assert overlay.endswith("…")
    assert not overlay.endswith(" und…")


def test_write_mechanism_shot_plans_outputs_markdown(tmp_path):
    explainer = _auto_explainer()

    paths = write_mechanism_shot_plans([explainer], tmp_path)

    assert len(paths) == 1
    assert paths[0].suffix == ".md"
    text = paths[0].read_text(encoding="utf-8")
    assert "## Mechanism shot plan" in text
    assert "pattern_interrupt" in text
    assert "mechanism_animation" in text
    assert "Sound cue" in text
