from pathlib import Path

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


def block(start_marker: str, end_marker: str) -> str:
    start = TEXT.index(start_marker)
    end = TEXT.index(end_marker, start)
    return TEXT[start:end]


def test_game_clock_helper_only_seeds_on_set():
    helper = block(
        "function vmixGameCountdownControlCommands",
        "function buildShortcutRuntimeContext",
    )
    pause_branch = helper[helper.index('if (action === "pause"'):helper.index('if (action === "set"')]
    set_branch = helper[helper.index('if (action === "set"'):helper.index('return [{ Function: "StartCountdown"')]
    start_branch = helper[helper.index('return [{ Function: "StartCountdown"'):]

    assert 'Function: "PauseCountdown"' in pause_branch
    assert 'ChangeCountdown' not in pause_branch
    assert 'SetCountdown' not in pause_branch
    assert 'StopCountdown' not in pause_branch

    assert 'Function: "ChangeCountdown"' in set_branch
    assert 'Function: "StartCountdown"' not in set_branch
    assert 'Function: "PauseCountdown"' not in set_branch

    assert 'Function: "StartCountdown"' in start_branch
    assert 'ChangeCountdown' not in start_branch
    assert 'PauseCountdown' not in start_branch


def test_space_game_timer_uses_control_only_helper():
    section = block('case "hockey_vmix_timers_start":', 'case "delay":')
    game = section[:section.index('if (step.sync_vmix_penalties)')]
    assert 'vmixGameCountdownControlCommands' in game
    assert '"pause"' in game
    assert '"start"' in game
    # Generic helper may still be used later for penalty countdowns, but never in main game branch.
    assert 'vmixCountdownSyncCommands' not in game


def test_explicit_time_change_seeds_even_before_first_space():
    section = block(
        'async function syncActiveVmixGameCountdown',
        'function configuredHockeyVmixGameCountdownTargets',
    )
    assert 'explicitSeedEvent' in section
    assert 'timer_set_time' in section
    assert 'timer_reset' in section
    assert 'state.config.shortcut_sequences' in section
    assert 'vmixGameCountdownControlCommands(input, selectedName, valueProvider, "set")' in section


def test_pause_event_never_writes_browser_time_to_vmix():
    section = block(
        'async function syncActiveVmixGameCountdown',
        'function configuredHockeyVmixGameCountdownTargets',
    )
    pause = section[section.index('eventName === "timer_pause"'):section.index('timer_stop', section.index('eventName === "timer_pause"'))]
    assert '"pause"' in pause
    assert '"set"' not in pause
    assert 'ChangeCountdown' not in pause
