"""Independent emergency programme: exact media, backup-only destination and live progress health."""
from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "live"))
import emergency_stream as E  # noqa: E402


def test_card_is_full_hd_cbr_h264_with_silent_aac(tmp_path: Path):
    cmd = E.build_card_cmd(output=tmp_path / "technical_hold.mp4", logo=tmp_path / "logo.png",
                           font=tmp_path / "font.ttf")
    joined = " ".join(cmd)
    assert f"s={E.WIDTH}x{E.HEIGHT}:r={E.FPS}" in joined
    assert "libx264" in cmd and "yuv420p" in cmd and "high" in cmd
    assert ["-g", "60"] == cmd[cmd.index("-g"):cmd.index("-g") + 2]
    assert "nal-hrd=cbr:force-cfr=1:filler=1" in cmd
    assert "anullsrc=r=48000:cl=stereo" in cmd
    assert "aac" in cmd and "48000" in cmd
    assert "TEMPORARY INTERRUPTION" in joined


def test_card_refuses_an_on_air_format_that_is_too_short_or_too_small(tmp_path: Path):
    with pytest.raises(ValueError, match="four seconds"):
        E.build_card_cmd(output=tmp_path / "x.mp4", logo=tmp_path / "x.png",
                         font=tmp_path / "font.ttf", duration_s=3)
    with pytest.raises(ValueError, match="bitrate"):
        E.build_card_cmd(output=tmp_path / "x.mp4", logo=tmp_path / "x.png",
                         font=tmp_path / "font.ttf", bitrate_k=999)


def test_backup_destination_is_constructed_without_logging_or_guessing_the_key():
    url, secret = E.destination_from_env({
        "YOUTUBE_BACKUP_INGEST": "rtmps://b.rtmps.youtube.com/live2/",
        "YOUTUBE_STREAM_KEY": "SECRET",
    })
    assert url == "rtmps://b.rtmps.youtube.com/live2/SECRET"
    assert secret == "SECRET"


def test_a_second_encoder_is_refused_on_the_primary_destination():
    with pytest.raises(E.EmergencyStreamError, match="backup ingest"):
        E.destination_from_env({
            "YOUTUBE_BACKUP_INGEST": "rtmps://a.rtmps.youtube.com/live2",
            "YOUTUBE_STREAM_KEY": "SECRET",
        })


def test_complete_destination_requires_a_stream_key_path():
    with pytest.raises(E.EmergencyStreamError, match="no stream key"):
        E.destination_from_env({"YOUTUBE_BACKUP_RTMPS_URL": "rtmps://b.example/"})


@pytest.mark.parametrize("env", [
    {},
    {"YOUTUBE_BACKUP_INGEST": "rtmps://b.rtmps.youtube.com/live2"},
    {"YOUTUBE_STREAM_KEY": "SECRET"},
    {"YOUTUBE_BACKUP_RTMPS_URL": "https://b.example/live2/SECRET"},
])
def test_missing_or_non_rtmps_credentials_fail_closed(env):
    with pytest.raises(E.EmergencyStreamError):
        E.destination_from_env(env)


def test_stream_loops_in_real_time_and_copies_the_prevalidated_bitstream(tmp_path: Path):
    media = tmp_path / "technical_hold.mp4"
    cmd = E.stream_cmd(media=media, destination="rtmps://backup.example/live/SECRET")
    joined = " ".join(cmd)
    assert "-re -stream_loop -1" in joined
    assert "-map 0:v:0 -map 0:a:0 -c copy" in joined
    assert "-progress pipe:1 -stats_period 2" in joined
    assert cmd[-3:] == ["-f", "flv", "rtmps://backup.example/live/SECRET"]


def test_verify_requires_matching_video_and_audio(monkeypatch, tmp_path: Path):
    media = tmp_path / "technical_hold.mp4"
    media.write_bytes(b"video")
    good = {
        "streams": [
            {"codec_type": "video", "codec_name": "h264", "width": 1920, "height": 1080,
             "pix_fmt": "yuv420p", "avg_frame_rate": "30/1"},
            {"codec_type": "audio", "codec_name": "aac", "sample_rate": "48000"},
        ],
        "format": {"duration": "12.0"},
    }
    monkeypatch.setattr(E, "probe_media", lambda *_a, **_kw: good)
    assert E.verify_media(media)["video"].startswith("h264 1920x1080")

    bad = {**good, "streams": [good["streams"][0]]}
    monkeypatch.setattr(E, "probe_media", lambda *_a, **_kw: bad)
    with pytest.raises(E.EmergencyStreamError, match="no audio"):
        E.verify_media(media)


def test_health_requires_recent_encoder_progress(tmp_path: Path):
    health = tmp_path / "health.json"
    health.write_text(json.dumps({"status": "streaming", "updatedUtcMs": 100_000}), encoding="utf-8")
    assert E.status(health, now_ms=105_000)["ageMs"] == 5_000
    with pytest.raises(E.EmergencyStreamError, match="stale"):
        E.status(health, now_ms=120_001)

    health.write_text(json.dumps({"status": "starting", "updatedUtcMs": 120_000}), encoding="utf-8")
    with pytest.raises(E.EmergencyStreamError, match="not 'streaming'"):
        E.status(health, now_ms=120_001)


def test_emergency_module_has_no_application_or_renderer_dependency():
    source = Path(E.__file__).read_text(encoding="utf-8")
    forbidden = ("postgres_store", "live_state", "serve_v3_live", "gcp_gateway", "selenium", "chromium")
    imports = "\n".join(line for line in source.splitlines() if line.startswith(("import ", "from ")))
    assert not any(name in imports for name in forbidden)


def test_systemd_restarts_and_keeps_the_repository_and_media_read_only():
    unit = (Path(E.__file__).resolve().parents[1] / "deploy" / "emergency-standby.service").read_text(
        encoding="utf-8"
    )
    assert "Restart=always" in unit and "StartLimitIntervalSec=0" in unit
    assert unit.index("StartLimitIntervalSec=0") < unit.index("[Service]")
    assert "ExecStartPre=" in unit and "emergency_stream.py verify " in unit
    assert "ProtectSystem=strict" in unit and "NoNewPrivileges=true" in unit
    assert "ReadOnlyPaths=/opt/viewregatta/TRAP /var/lib/viewregatta/emergency" in unit
    assert "EnvironmentFile=/etc/viewregatta/emergency-standby.env" in unit
    assert "YOUTUBE_STREAM_KEY" not in unit


def test_installer_never_starts_before_an_operator_supplies_and_checks_the_backup_url():
    installer = (Path(E.__file__).resolve().parents[1] / "deploy" /
                 "install_emergency_standby.sh").read_text(encoding="utf-8")
    executable = "\n".join(
        line for line in installer.split("cat <<'EOF'", 1)[0].splitlines()
        if line.strip() and not line.lstrip().startswith("#")
    )
    assert "systemctl enable" not in executable and "systemctl start" not in executable
    assert "YOUTUBE_BACKUP_INGEST=" not in executable
    assert "YOUTUBE_STREAM_KEY=" not in executable
    assert "mktemp -d" in executable
    assert "$REPO/.emergency-install-check.mp4" not in executable
    assert "emergency-standby-watchdog.timer" in installer


def test_watchdog_restarts_only_an_active_stalled_encoder():
    deploy = Path(E.__file__).resolve().parents[1] / "deploy"
    script = (deploy / "watch_emergency_standby.sh").read_text(encoding="utf-8")
    service = (deploy / "emergency-standby-watchdog.service").read_text(encoding="utf-8")
    timer = (deploy / "emergency-standby-watchdog.timer").read_text(encoding="utf-8")
    assert "systemctl is-active --quiet" in script
    assert 'systemctl restart "$SERVICE"' in script
    assert "ExecStart=/opt/viewregatta/TRAP/v3/broadcast/deploy/watch_emergency_standby.sh" in service
    assert "OnUnitActiveSec=15" in timer
