from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
JS = (ROOT / "hockey_data" / "static" / "tournament-menu.js").read_text(encoding="utf-8")
SERVICE = (ROOT / "hockey_data" / "service.py").read_text(encoding="utf-8")
ROUTER = (ROOT / "hockey_data" / "router.py").read_text(encoding="utf-8")
APP = (ROOT / "app.py").read_text(encoding="utf-8")


def test_previous_match_runtime_rosters_are_explicitly_cleared():
    assert "function clearRuntimeMatchSpecificData()" in JS
    assert "selected_game: null" in JS
    assert "home: null" in JS
    assert "away: null" in JS
    assert "referees: []" in JS
    assert "match_details: null" in JS
    assert "clearRuntimeMatchSpecificData();" in JS


def test_old_polling_stops_before_new_match_selection():
    start = JS.index("async function openGame")
    stop = JS.index("stopSelectedGamePolling();", start)
    generation = JS.index("const generation = ++state.gameOpenGeneration;", start)
    assert stop < generation


def test_selected_game_cache_is_match_scoped_and_local():
    assert "/api/hockey/games/${encodeURIComponent(id)}/details?language=" in JS
    assert "cachedMatchHasRosters" in JS
    assert "cachedRostersReady" in JS


def test_first_time_match_waits_for_core_roster_before_polling():
    assert "if (!manual && !cachedRostersReady)" in JS
    assert "await enrichOpenedGame(String(id), state.selectedId, generation, { opening: true });" in JS
    branch = JS.index("if (!manual && !cachedRostersReady)")
    enrich = JS.index("await enrichOpenedGame", branch)
    poll = JS.index("startSelectedGamePolling();", enrich)
    assert enrich < poll


def test_opening_sync_skips_schedule_roundtrip_and_optional_shots():
    assert "opening: bool = False" in ROUTER
    assert "opening=opening" in ROUTER
    assert "if opening:" in SERVICE
    assert "schedule = self.game(game_external_id, language=language)" in SERVICE
    assert "skip_optional_shots=opening" in SERVICE
    assert "if not skip_optional_shots:" in SERVICE


def test_runtime_version_build110():
    assert 'BUILD_VERSION = "2026.08.24.13"' in APP
