from webui import server


def test_startup_without_log(tmp_path):
    assert server.buildStartup(tmp_path)['state'] == 'idle'


def test_startup_reports_progress(tmp_path):
    (tmp_path / '.one-click.log').write_text(
        '2026-07-21T07:00:12.55+02:00 start\n'
        '2026-07-21T07:00:13.10+02:00 hid-ready\n', encoding='utf-8')

    result = server.buildStartup(tmp_path)

    assert result['state'] == 'busy'
    assert result['text'] == 'Eingabe-Hardware bereit'
    assert result['at'] == '07:00:13'


def test_startup_reports_error_from_log(tmp_path):
    (tmp_path / '.one-click.log').write_text(
        '2026-07-21T07:00:13.92+02:00 error=Kein Arduino erkannt.\n',
        encoding='utf-8')

    result = server.buildStartup(tmp_path)

    assert result == {'state': 'error', 'text': 'Kein Arduino erkannt.',
                      'at': '07:00:13'}


def test_startup_result_file_wins(tmp_path):
    (tmp_path / '.one-click.log').write_text(
        '2026-07-21T07:00:12.55+02:00 running\n', encoding='utf-8')
    (tmp_path / '.one-click-result.json').write_text(
        '{"ok": false, "message": "Tibia login failed."}', encoding='utf-8')

    assert server.buildStartup(tmp_path) == {
        'state': 'error', 'text': 'Tibia login failed.'}


def test_startup_running(tmp_path):
    (tmp_path / '.one-click.log').write_text(
        '2026-07-21T07:00:12.55+02:00 running\n', encoding='utf-8')

    assert server.buildStartup(tmp_path)['state'] == 'running'


def test_task_actions_are_registered():
    assert set(server.TASK_ACTIONS) == {
        'startAll', 'stopAll', 'stopBot', 'installUpdate',
    }


def test_start_runs_through_the_wrapper():
    """Nicht per schtasks direkt starten.

    Windows ignoriert einen Start stillschweigend, solange die Aufgabe
    noch als "laeuft" gilt - etwa als Karteileiche eines abgebrochenen
    Laufs. Genau das fuehrte zu "ich druecke Start und nichts passiert".
    Der Wrapper raeumt das auf und startet ausserdem neu, wenn der
    Bildschirm gewechselt wurde.
    """
    befehl = server.TASK_ACTIONS['startAll']
    assert 'schtasks' not in befehl
    assert befehl[-1].endswith('Start-OneClick-Task.ps1')


def test_stop_all_closes_everything():
    """"Alles beenden" muss Bot, Tibia UND OBS schliessen."""
    assert server.TASK_ACTIONS['stopAll'][-1].endswith('Stop-Everything.ps1')


def test_startup_reads_ansi_log(tmp_path):
    # PowerShell schreibt manchmal cp1252 statt UTF-8 — darf nicht kaputtgehen.
    (tmp_path / '.one-click.log').write_bytes(
        '2026-07-22T19:00:00+02:00 error=Board-Aufdruck prüfen.\n'.encode('cp1252'))

    assert server.buildStartup(tmp_path)['text'] == 'Board-Aufdruck prüfen.'


def test_startup_reads_utf8_bom_log(tmp_path):
    (tmp_path / '.one-click.log').write_bytes(
        '﻿2026-07-22T19:00:00+02:00 error=Kabel prüfen.\n'.encode('utf-8'))

    assert server.buildStartup(tmp_path)['text'] == 'Kabel prüfen.'
