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 _block(start: str, end: str) -> str:
    return APP_JS.split(start, 1)[1].split(end, 1)[0]


def test_timer_transport_is_independent_from_generic_vmix_queue():
    block = _block("function sendRuntimeVmixTimerSequence", "function splitVmixInputs")
    assert 'fetch("/api/hockey/vmix/sequence"' in block
    assert 'keepalive: true' in block
    assert 'state.vmixCommandQueue' not in block
    assert 'sequence_id' not in block.split('body: JSON.stringify({', 1)[1]
    assert 'Runtime continues locally' in block


def test_timer_start_stop_protocol_is_minimal():
    helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
    assert 'if (action === "stop" || action === "pause")' in helper
    stop_branch = helper.split('if (action === "stop" || action === "pause")', 1)[1].split('return [', 1)[1].split('];', 1)[0]
    assert 'Function: "SuspendCountdown"' in stop_branch
    assert 'Function: "StopCountdown"' not in stop_branch
    assert 'Function: "SetCountdown"' not in stop_branch
    start_branch = helper.rsplit('return [', 1)[1]
    assert start_branch.index('Function: "SetCountdown"') < start_branch.index('Function: "StartCountdown"')
    assert 'PauseCountdown' not in helper


def test_combined_hockey_timer_shortcut_never_waits_for_agent():
    block = APP_JS.split('case "hockey_vmix_timers_start":', 1)[1].split('case "delay":', 1)[0]
    assert 'sendRuntimeVmixTimerSequence(commands);' in block
    assert 'await sendRuntimeVmixSequence(commands' not in block
    assert 'fire-and-forget' in block
    # Local state changes remain ahead of any vMix transport.
    assert block.index('if (step.start_web_game)') < block.index('if (commands.length) sendRuntimeVmixTimerSequence(commands);')


def test_main_and_penalty_resync_do_not_use_generic_queue():
    game = _block("async function syncActiveVmixGameCountdown", "function penaltyMirrorKey")
    penalty = _block("async function rebalanceVmixPenaltyTargets", "function finishActionMatchesSource")
    assert 'sendRuntimeVmixTimerSequence(commands);' in game
    assert 'await sendRuntimeVmixSequence(commands)' not in game
    assert 'sendRuntimeVmixTimerSequence(commands);' in penalty
    assert 'await sendRuntimeVmixSequence(commands)' not in penalty


def test_busy_shortcut_can_toggle_timer_without_waiting_for_title_ack():
    block = _block("function shortcutSequenceTimerControlSteps", "function handleConfiguredShortcutCombo")
    assert 'runShortcutTimerControlsWhileBusy(sequence, meta)' in block
    assert 'timer controls are never queued behind title/Agent ACK traffic' in block
    assert '["timer_command", "hockey_vmix_timers_start"]' in block


def test_build101_runtime_version():
    assert 'BUILD_VERSION = "2026.08.24.4"' in APP
