from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
CV_FORM = ROOT / 'templates' / 'cv-form.php'


def source():
    return CV_FORM.read_text()


def test_voice_tab_does_not_auto_start_microphone():
    text = source()
    handler = text.split("$$('[data-ssc-guided-mode]').forEach", 1)[1].split("$('[data-ssc-guided-voice-record]')", 1)[0]
    assert "if (mode === 'voice') { startRecognition(); }" not in handler
    assert "red Tap to speak" in handler


def test_tap_to_speak_has_clear_status_and_explicit_stop_copy():
    text = source()
    assert "data-ssc-guided-voice-status" in text
    assert "Tap to speak" in text
    assert "Stop & edit text" in text
    assert "Your words appear in the editable box above" in text


def test_microphone_errors_stay_in_voice_mode_with_fallback_guidance():
    text = source()
    assert "Microphone blocked. Tap the browser lock icon" in text
    assert "No speech heard yet. Try again" in text
    assert "Voice could not start. Tap the red button again" in text
    assert "setVoiceStatus('Voice is not supported in this browser. Use the text box above.', 'error');" in text
    unsupported = text.split("if (!Rec) {", 1)[1].split("}\n      stopRecognition();", 1)[0]
    assert "setMode('type');" in unsupported  # unsupported browser only


def test_stop_intent_prevents_infinite_restart_loop():
    text = source()
    assert "intentionallyStopped" in text
    assert "var shouldRestart = state.recognition === rec && state.mode === 'voice' && !state.intentionallyStopped;" in text
    assert "state.intentionallyStopped = true;\n      state.listening = false;" in text



def test_voice_ui_waits_for_browser_onstart_before_showing_listening_state():
    text = source()
    setup = text.split("var live = $('[data-ssc-guided-voice-live]');", 1)[1].split("rec.onstart = function", 1)[0]
    assert "hideVoiceEl(live)" in setup
    assert "Starting microphone" in setup
    assert "Listening…" not in setup
    onstart = text.split("rec.onstart = function () {", 1)[1].split("};\n      rec.onresult", 1)[0]
    assert "Listening…" in onstart
    assert "hideVoiceEl($('[data-ssc-guided-voice-record]'))" in onstart
    assert "showVoiceEl($('[data-ssc-guided-voice-stop]'))" in onstart


def test_voice_ui_hides_buttons_with_important_display_override():
    text = source()
    assert "function hideVoiceEl(el)" in text
    assert "style.setProperty('display', 'none', 'important')" in text
    assert "hideVoiceEl($('[data-ssc-guided-voice-stop]'));" in text
    assert "hideVoiceEl($('[data-ssc-guided-voice-record]'));" in text
    assert "showVoiceEl($('[data-ssc-guided-voice-stop]'));" in text
