import json

from webui import server


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


def test_build_config_merges_death_defaults(tmp_path):
    profile = _write(tmp_path / 'file.json', {'_default': {'1': {
        'enabled': True,
        'config': {
            'ng_deathConfig': {'refillCap': 55},
            'ui_theme': 'violett', 'ui_mode': 'hell', 'ui_glass': 40,
            'ng_cave': {'waypoints': {'items': [
                {'label': 'Start', 'type': 'walk',
                 'coordinate': [1, 2, 7]},
            ]}},
            'ng_comboSpells': {'items': [
                {'name': 'Default', 'enabled': True, 'spells': [{'a': 1}]},
            ]},
        }}}})

    result = server.buildConfig(profile_path=str(profile))

    assert result['death']['refillCap'] == 55
    assert result['death']['minPotions'] == 10  # Default bleibt
    assert result['design'] == {'theme': 'violett', 'mode': 'hell', 'glass': 40}
    assert result['waypoints'][0]['label'] == 'Start'
    assert result['combos'][0] == {'name': 'Default', 'enabled': True,
                                   'spells': 1}


def test_build_config_tolerates_missing_profile(tmp_path):
    result = server.buildConfig(profile_path=str(tmp_path / 'fehlt.json'))

    assert result['death']['refillCap'] == 30
    assert result['design']['theme'] == 'rosa'
    assert result['waypoints'] == []


def test_write_command_with_path(tmp_path):
    target = tmp_path / 'cmd.json'
    server.writeCommand('setConfig', 55, file=target, **{'path': 'x.y'})

    assert json.loads(target.read_text()) == {
        'action': 'setConfig', 'value': 55, 'path': 'x.y'}
