import json

from webui import server


def _write(path, data):
    path.write_text(json.dumps(data), encoding='utf-8')
    return path


def test_build_state_aggregates(tmp_path):
    state = _write(tmp_path / 'state.json', {
        'pause': False, 'task': 'walkToWaypoint', 'waypointIndex': 12,
        'coordinate': [100, 200, 7], 'hpPercentage': 88,
        'manaPercentage': 64, 'cavebotEnabled': True,
        'runToCreatures': False, 'comboEnabled': True,
    })
    session = _write(tmp_path / 'session.json', {'playedSeconds': 3660})
    stats = _write(tmp_path / 'stats.json', {'lootPerHour': 42})
    events = tmp_path / 'events.jsonl'
    events.write_text(json.dumps({'at': '2026-07-22T04:15:00',
                                  'type': 'deathByMonster'}) + '\n')
    profile = _write(tmp_path / 'file.json', {'_default': {'1': {
        'enabled': True,
        'config': {'healing': {'potions': {
            'firstHealthPotion': {'enabled': True}}}},
    }}})

    result = server.buildState(
        profile_path=str(profile), state_path=state, session_path=session,
        stats_path=stats, events_path=events)

    assert result['pause'] is False
    assert result['task'] == 'walkToWaypoint'
    assert result['hpPercentage'] == 88
    assert result['toggles'] == {
        'cavebot': True, 'runToCreatures': False,
        'combo': True, 'healing': True,
    }
    assert result['playedSeconds'] == 3660
    assert result['stats']['lootPerHour'] == 42
    assert result['events'][0]['type'] == 'deathByMonster'


def test_build_state_tolerates_missing_files(tmp_path):
    result = server.buildState(
        profile_path=str(tmp_path / 'fehlt.json'),
        state_path=tmp_path / 'fehlt2.json',
        session_path=tmp_path / 'fehlt3.json',
        stats_path=tmp_path / 'fehlt4.json',
        events_path=tmp_path / 'fehlt5.json')

    assert result['pause'] is True
    assert result['toggles']['healing'] is False
    assert result['events'] == []


def test_write_command(tmp_path):
    target = tmp_path / 'cmd.json'
    server.writeCommand('toggleCavebot', True, file=target)

    assert json.loads(target.read_text()) == {
        'action': 'toggleCavebot', 'value': True}
