from pathlib import Path

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


def test_game_countdown_resume_is_reseeded_before_start():
    block = APP_JS.split("async function syncActiveVmixGameCountdown", 1)[1].split("function penaltyMirrorKey", 1)[0]
    assert '["timer_start", "timer_restart", "timer_resume"].includes(eventName)' in block
    assert 'vmixCountdownSyncCommands(input, selectedName, valueProvider, "start")' in block
    helper = APP_JS.split("function vmixCountdownSyncCommands", 1)[1].split("function buildShortcutRuntimeContext", 1)[0]
    start_branch = helper.rsplit("return [", 1)[1]
    assert start_branch.index('Function: "SetCountdown"') < start_branch.index('Function: "StartCountdown"')
    assert 'eventName === "timer_resume"' not in block


def test_hockey_timer_shortcut_reseeds_game_and_penalty_on_resume():
    block = APP_JS.split('case "hockey_vmix_timers_start":', 1)[1].split('case "delay":', 1)[0]
    # Resume must no longer have a StartCountdown-only branch.
    assert '} else if (action === "resume") {' not in block
    assert block.count('vmixCountdownSyncCommands(') >= 2
    assert '() => gameTimerState.currentMs' in block
    assert '() => event.remainingMs' in block


def test_penalty_rebalance_pairs_every_start_with_current_web_value():
    block = APP_JS.split("async function rebalanceVmixPenaltyTargets", 1)[1].split("function currentHockeyPenaltyEntries", 1)[0]
    assert "const startingCountdown" in block
    assert "force || assignmentChanged || startingCountdown" in block
    assert 'Function: "SetCountdown"' in block
    assert 'Function: "StartCountdown"' in block


def test_native_mode_still_has_no_per_second_countdown_transport():
    assert 'eventName === "timer_tick" && state.vmixTimerMirrors.has(component.action_id)' in APP_JS
    tick_branch = APP_JS.split('eventName === "timer_tick" && state.vmixTimerMirrors.has(component.action_id)', 1)[1].split('} else if (eventName !== "timer_tick"', 1)[0]
    assert "SetCountdown" not in tick_branch


def test_build93_runtime_version():
    assert 'BUILD_VERSION = "2026.08.20.14"' in APP
