from pathlib import Path

from hockey_data.agent_bridge import VmixAgentHub

ROOT = Path(__file__).resolve().parents[1]
APP_JS = (ROOT / "ui_builder/static/app.js").read_text(encoding="utf-8")
BRIDGE = (ROOT / "hockey_data/agent_bridge.py").read_text(encoding="utf-8")


def test_penalty_display_routes_only_one_transition_timer_to_advantage_target():
    start = APP_JS.index("function penaltyDisplayEntriesByTargetSide")
    end = APP_JS.index("function hockeyPenaltySideMappingDetail", start)
    block = APP_JS[start:end]
    assert 'function penaltyLocalAdvantageSide' in APP_JS
    assert 'const all = [...home, ...away].sort' in block
    assert 'if (!advantageSide)' in block
    assert 'home: advantageSide === "home"' in block
    assert 'away: advantageSide === "away"' in block


def test_penalty_rebalance_and_initial_timer_use_same_display_plan():
    assert APP_JS.count("penaltyDisplayEntriesByTargetSide(step)") >= 2
    assert "sourceSide" in APP_JS
    assert "targetSide" in APP_JS


def test_server_tracks_acknowledged_overlay_owner_for_lower_dock():
    hub = object.__new__(VmixAgentHub)
    hub._runtime_overlay_state = {}
    hub._track_runtime_overlay_command(
        "device-1",
        {"Function": "OverlayInput4In", "Input": "TITLE-A"},
        sequence_id="seq-title-a",
        sequence_name="Title A",
        button_id="btn-a",
    )
    payload = hub._runtime_overlay_payload("device-1")
    assert payload["overlays"]["4"]["input"] == "TITLE-A"
    assert payload["overlays"]["4"]["sequence_id"] == "seq-title-a"
    assert payload["overlays"]["4"]["button_id"] == "btn-a"

    hub._track_runtime_overlay_command("device-1", {"Function": "OverlayInput4Out", "Input": "TITLE-A"})
    assert hub._runtime_overlay_payload("device-1")["overlays"] == {}


def test_runtime_sequence_carries_owner_metadata_and_polling_recovers_state():
    for token in (
        'sequence_id: String(execution?.sequence_id || "")',
        'sequence_name: String(execution?.sequence_name || "")',
        'button_id: String(execution?.button_id || "")',
        'function applyServerRuntimeOverlayState(payload)',
        'function startQuickPanelOverlayPolling()',
        '/api/hockey/vmix/overlay-state?device_id=',
        'state.quickPanelServerOnAirSequences.has(id)',
    ):
        assert token in APP_JS
    assert 'sequence_id: str = Field(default="", max_length=160)' in BRIDGE
    assert '@router.get("/api/hockey/vmix/overlay-state")' in BRIDGE
