import json

from src.ui import livestate


def test_read_events_newest_first(tmp_path):
    events = tmp_path / 'events.jsonl'
    events.write_text(
        json.dumps({'at': '2026-07-21T10:00:00', 'type': 'a'}) + '\n' +
        json.dumps({'at': '2026-07-21T11:00:00', 'type': 'b'}) + '\n'
    )
    result = livestate.readEvents(events)
    assert [event['type'] for event in result] == ['b', 'a']


def test_read_events_tolerates_missing_and_broken(tmp_path):
    assert livestate.readEvents(tmp_path / 'fehlt.jsonl') == []
    broken = tmp_path / 'broken.jsonl'
    broken.write_text('{kaputt\n' + json.dumps({'type': 'ok'}) + '\n')
    assert [event['type'] for event in livestate.readEvents(broken)] == ['ok']


def test_session_summary_defaults_and_break(tmp_path):
    session = tmp_path / 'session.json'
    assert livestate.sessionSummary(session) == {
        'playedSeconds': 0, 'breakRemainingSeconds': 0,
    }
    session.write_text(json.dumps({
        'playedSeconds': 3720, 'breakUntil': 1000,
    }))
    summary = livestate.sessionSummary(session, now=400)
    assert summary['playedSeconds'] == 3720
    assert summary['breakRemainingSeconds'] == 600


def test_format_duration():
    assert livestate.formatDuration(0) == '0 min'
    assert livestate.formatDuration(59 * 60) == '59 min'
    assert livestate.formatDuration(3720) == '1 h 02 min'
    assert livestate.formatDuration(9000) == '2 h 30 min'


def test_session_report_counts_events_in_window(tmp_path):
    import time as timeModule
    now = timeModule.time()
    stats = tmp_path / 'stats.json'
    stats.write_text(json.dumps({'minutes': 30, 'lootEvents': 7}))
    session = tmp_path / 'session.json'
    session.write_text(json.dumps({'playedSeconds': 1800}))
    events = tmp_path / 'events.jsonl'
    fresh = timeModule.strftime('%Y-%m-%dT%H:%M:%S', timeModule.localtime(now))
    old = timeModule.strftime(
        '%Y-%m-%dT%H:%M:%S', timeModule.localtime(now - 7200))
    events.write_text(
        json.dumps({'at': old, 'type': 'deathByMonster'}) + '\n'
        + json.dumps({'at': fresh, 'type': 'deathByPlayer'}) + '\n'
        + json.dumps({'at': fresh, 'type': 'failsafe'}) + '\n'
    )
    report = livestate.sessionReport(
        now=now, stats_path=stats, session_path=session,
        events_path=events)
    assert report['playedSeconds'] == 1800
    assert report['counts'] == {'deathByPlayer': 1, 'failsafe': 1}
    assert len(report['events']) == 2


def test_overlay_position_roundtrip(tmp_path):
    path = tmp_path / 'overlay.json'
    assert livestate.loadOverlayPosition(path) is None
    livestate.saveOverlayPosition(120, 80, path)
    assert livestate.loadOverlayPosition(path) == (120, 80)
    livestate.saveOverlayPosition(-50, 30, path)
    assert livestate.loadOverlayPosition(path) == (0, 30)


def test_overlay_position_ignores_garbage(tmp_path):
    path = tmp_path / 'overlay.json'
    path.write_text('{"x": "links"}')
    assert livestate.loadOverlayPosition(path) is None
