from src.gameplay.stats import SessionStats

NOW = 1_800_000_000


def make(tmp_path):
    return SessionStats(
        stats_file=tmp_path / 'stats.json',
        heatmap_file=tmp_path / 'heatmap.json',
    )


def test_loot_events_count_and_rate(tmp_path):
    stats = make(tmp_path)
    stats.startedAt = NOW - 1800
    for _ in range(9):
        stats.lootEvent()
    summary = stats.summary(NOW)
    assert summary['lootEvents'] == 9
    assert summary['lootPerHour'] == 18.0
    assert summary['minutes'] == 30


def test_points_recorded_only_on_change(tmp_path):
    stats = make(tmp_path)
    stats.tick((32000, 32000, 7), NOW)
    stats.tick((32000, 32000, 7), NOW + 1)
    stats.tick((32001, 32000, 7), NOW + 2)
    assert len(stats.points) == 2


def test_stuck_after_threshold(tmp_path):
    stats = make(tmp_path)
    stats.tick((32000, 32000, 7), NOW)
    stats.tick((32000, 32000, 7), NOW + 30)
    assert stats.stucks == []
    stats.tick((32000, 32000, 7), NOW + 95)
    assert len(stats.stucks) == 1
    assert stats.stucks[0]['seconds'] == 95
    # Re-arm: kein Dauerfeuer beim Stehen.
    stats.tick((32000, 32000, 7), NOW + 100)
    assert len(stats.stucks) == 1


def test_jump_detects_teleport(tmp_path):
    stats = make(tmp_path)
    stats.tick((32000, 32000, 7), NOW)
    stats.tick((32001, 32000, 7), NOW + 1)
    assert stats.jumps == []
    stats.tick((32000, 32000, 4), NOW + 2)
    assert len(stats.jumps) == 1
    assert stats.jumps[0]['to'] == [32000, 32000, 4]


def test_none_coordinate_ignored(tmp_path):
    stats = make(tmp_path)
    stats.tick(None, NOW)
    assert stats.points == []


def test_save_writes_both_files(tmp_path):
    stats = make(tmp_path)
    stats.lootEvent()
    stats.tick((32000, 32000, 7), NOW)
    stats.save(NOW)
    import json
    summary = json.loads((tmp_path / 'stats.json').read_text())
    heatmap = json.loads((tmp_path / 'heatmap.json').read_text())
    assert summary['lootEvents'] == 1
    assert heatmap['points'] == [[32000, 32000, 7, NOW]]
