from pathlib import Path

import pytest

from tools.pipeline.run import probe_duration, process_clip, resolve_ffmpeg

# A real pool base (forest was retired with the rotating-pool rename, session 0016);
# cosmos/base.mp4 is the cosmos pool primary and the most stable PD clip on disk.
_BASE = Path("simulator/sample_media/cosmos/base.mp4")


def _ffmpeg_available() -> bool:
    try:
        resolve_ffmpeg()
        return True
    except Exception:
        return False


_HAS_FF = _ffmpeg_available()


@pytest.mark.skipif(not _BASE.exists(),
                    reason="cosmos base absent (run simulator/build_pool_manifest.py)")
def test_probe_duration_reads_real_base():
    assert probe_duration(_BASE) > 0


@pytest.mark.skipif(not _HAS_FF,
                    reason="neither system ffmpeg nor imageio-ffmpeg available")
@pytest.mark.skipif(not _BASE.exists(),
                    reason="cosmos base absent (run simulator/build_pool_manifest.py)")
def test_process_clip_emits_proxy_and_master(tmp_path):
    out = process_clip(_BASE, tmp_path, overlap=0.5, start=0.0, duration=4.0)
    assert out["proxy"].exists() and out["master"].exists()
    # Proxy is exactly 1920×1080 — verified with cv2, no ffprobe dependency.
    import cv2
    cap = cv2.VideoCapture(str(out["proxy"]))
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    cap.release()
    assert (w, h) == (1920, 1080)
