import json
from pathlib import Path

from autoshorts.growth_plan import load_testbatch
from autoshorts.review_package import build_review_package, format_review_package, write_review_packages


def _batch() -> dict:
    return load_testbatch(Path("data/drafts/testbatch_002.json"))


def _idea(script_id: str) -> dict:
    return next(item for item in _batch()["ideas"] if item["id"] == script_id)


def _manifest(script_id: str) -> dict:
    manifest_path = next(Path("data/render_manifests/testbatch_002_top3").glob(f"{script_id}-*.json"))
    return json.loads(manifest_path.read_text(encoding="utf-8"))


def test_build_review_package_collects_approval_metadata():
    package = build_review_package(
        _idea("ai-004"),
        _manifest("ai-004"),
        Path("data/previews/testbatch_002_top3/ai-004-stop-asking-ai-to-think-for-you.mp4"),
    )

    assert package["id"] == "ai-004"
    assert package["pillar"] == "ai_life_systems"
    assert package["duration_seconds"] == 43
    assert package["quality_score"] == 10
    assert package["visual_scene_count"] == 5
    assert "screen_recording" in package["visual_types"]
    assert "Freigabe alle" in package["approval_commands"]
    assert package["preview_path"].endswith(".mp4")


def test_format_review_package_is_telegram_safe_and_actionable():
    package = build_review_package(
        _idea("attention-002"),
        _manifest("attention-002"),
        Path("/tmp/attention-002.mp4"),
    )

    message = format_review_package(package)

    assert message.startswith("## AutoShortsBot Review — attention-002")
    assert "MEDIA:/tmp/attention-002.mp4" in message
    assert "**Hook:** The algorithm does not need you happy" in message
    assert "`Freigabe YouTube`" in message
    assert "**Risk Notes:**" in message
    assert "|" not in message


def test_write_review_packages_outputs_one_markdown_per_manifest(tmp_path):
    paths = write_review_packages(
        batch=_batch(),
        manifest_dir=Path("data/render_manifests/testbatch_002_top3"),
        preview_dir=Path("data/previews/testbatch_002_top3"),
        output_dir=tmp_path,
    )

    assert len(paths) == 3
    assert all(path.suffix == ".md" for path in paths)
    text = paths[0].read_text(encoding="utf-8")
    assert "AutoShortsBot Review" in text
    assert "Freigabe-Befehle" in text
