"""Test #11 from BUILD_SPEC EP001-render-rootcause-fix.

The reporter must count files on disk via Path.exists(), NOT sum
`segment_count` from r2v_multi metadata. Bug D regression coverage.
"""

from __future__ import annotations

from pathlib import Path
from types import SimpleNamespace

from recoil.pipeline.core.receipts import aggregate_disk_truth


def _mock_receipt(output_path, metadata):
    return SimpleNamespace(
        run_result=SimpleNamespace(output_path=output_path, metadata=metadata),
    )


# ── Test #11 — disk truth wins over segment_count ────────────────────

def test_reporter_counts_disk_truth(tmp_path: Path):
    """SYNTHESIS §8 test #11.

    4 mock r2v_multi receipts with segment_count=4 each ('would' total
    15 segments via the broken sum), but only 2 of their output_path
    files actually exist on disk. Reporter returns 2.
    """
    existing_1 = tmp_path / "ep_001" / "PASS_001_take1.mp4"
    existing_1.parent.mkdir(parents=True)
    existing_1.write_bytes(b"x")
    existing_2 = tmp_path / "ep_001" / "PASS_002_take1.mp4"
    existing_2.write_bytes(b"x")
    missing_3 = tmp_path / "ep_001" / "PASS_003_take1.mp4"
    missing_4 = tmp_path / "ep_001" / "PASS_004_take1.mp4"

    receipts = [
        _mock_receipt(str(existing_1), {"segment_count": 4, "files_on_disk": 1}),
        _mock_receipt(str(existing_2), {"segment_count": 4, "files_on_disk": 1}),
        _mock_receipt(str(missing_3), {"segment_count": 4, "files_on_disk": 0}),
        _mock_receipt(str(missing_4), {"segment_count": 3, "files_on_disk": 0}),
    ]

    broken_count = sum(r.run_result.metadata["segment_count"] for r in receipts)
    assert broken_count == 15  # would over-report by 13

    assert aggregate_disk_truth(receipts) == 2


def test_aggregate_disk_truth_handles_none(tmp_path: Path):
    """None receipts, None output_paths, missing run_result — all skipped."""
    receipts = [
        None,
        SimpleNamespace(run_result=None),
        SimpleNamespace(run_result=SimpleNamespace(output_path=None, metadata={})),
        _mock_receipt(str(tmp_path / "missing.mp4"), {"files_on_disk": 0}),
    ]
    assert aggregate_disk_truth(receipts) == 0


def test_aggregate_disk_truth_path_objects(tmp_path: Path):
    """output_path may be a Path or a str; both supported."""
    p1 = tmp_path / "a.mp4"
    p1.write_bytes(b"x")
    p2 = tmp_path / "b.mp4"
    p2.write_bytes(b"x")
    receipts = [
        _mock_receipt(p1, {}),
        _mock_receipt(str(p2), {}),
    ]
    assert aggregate_disk_truth(receipts) == 2
