from pathlib import Path

import pytest

from autoshorts.production.wan_output_parser import (
    WanRunResult,
    parse_wan_history_outputs,
    validate_wan_run_success,
)


def test_history_item_false_is_ignored_not_interpreted_as_output():
    history = {
        "outputs": {
            "9": {
                "images": [
                    {"filename": "clip.mp4", "subfolder": "autoshorts", "type": "output"},
                ],
                "animated": [True],
                "debug": [False, None],
            }
        }
    }

    outputs = parse_wan_history_outputs(history)

    assert len(outputs) == 1
    assert outputs[0].filename == "clip.mp4"


def test_missing_filename_blocks_history_parsing():
    history = {"outputs": {"9": {"images": [{"subfolder": "autoshorts", "type": "output"}]}}}

    with pytest.raises(ValueError, match="missing filename"):
        parse_wan_history_outputs(history)


def test_exit_code_nonzero_blocks_final_success_even_with_file(tmp_path):
    video = tmp_path / "clip.mp4"
    video.write_bytes(b"not real video")
    result = WanRunResult(exit_code=1, recovered=False, outputs=[video], stderr="AttributeError")

    gate = validate_wan_run_success(result, expected_final_seconds=38.0, probe=lambda _: (5.0, 12.0))

    assert gate.allowed is False
    assert "exit code" in gate.reason


def test_recovered_nonzero_exit_must_have_valid_video(tmp_path):
    video = tmp_path / "clip.mp4"
    video.write_bytes(b"placeholder")
    result = WanRunResult(exit_code=1, recovered=True, outputs=[video], stderr="download recovered")

    gate = validate_wan_run_success(result, expected_final_seconds=8.0, probe=lambda _: (8.1, 30.0))

    assert gate.allowed is True
    assert gate.reason == "wan_run_valid_recovered"


def test_too_short_wan_clip_for_full_final_blocks_or_hard_warns(tmp_path):
    video = tmp_path / "short.mp4"
    video.write_bytes(b"placeholder")
    result = WanRunResult(exit_code=0, recovered=False, outputs=[video], stderr="")

    gate = validate_wan_run_success(result, expected_final_seconds=38.0, probe=lambda _: (5.08, 12.0))

    assert gate.allowed is False
    assert gate.reason == "wan_clip_too_short_for_final"
