import json

import numpy as np
import pytest

from src.gameplay import monitoring


@pytest.fixture
def paths(tmp_path, monkeypatch):
    events = tmp_path / 'events.jsonl'
    shots = tmp_path / 'shots'
    monkeypatch.setenv(monitoring.EVENTS_FILE_ENV, str(events))
    monkeypatch.setenv(monitoring.SHOT_DIR_ENV, str(shots))
    return events, shots


def test_log_event_appends_jsonl(paths):
    events, _ = paths
    monitoring.logEvent('failsafe', {'reason': 'players'})
    monitoring.logEvent('sessionBreak', {'minutes': 30})
    lines = events.read_text(encoding='utf-8').strip().split('\n')
    assert len(lines) == 2
    first = json.loads(lines[0])
    assert first['type'] == 'failsafe'
    assert first['details']['reason'] == 'players'
    assert first['at']


def test_log_event_rotates_oversized_file(paths):
    events, _ = paths
    events.write_text('x' * (monitoring.MAX_EVENTS_BYTES + 1))
    monitoring.logEvent('failsafe')
    assert (events.parent / 'events.jsonl.old').exists()
    assert events.stat().st_size < 1000


def test_log_event_survives_missing_directory(paths, monkeypatch):
    monkeypatch.setenv(
        monitoring.EVENTS_FILE_ENV, '/definitiv/kein/pfad/events.jsonl',
    )
    monitoring.logEvent('failsafe')  # darf nicht werfen


def test_screenshot_saved_and_pruned(paths):
    _, shots = paths
    image = np.zeros((10, 10), dtype=np.uint8)
    for index in range(7):
        assert monitoring.saveEventScreenshot(image, f'players-{index}')
    assert len(list(shots.glob('*.png'))) == monitoring.MAX_SHOTS


def test_screenshot_none_is_noop(paths):
    _, shots = paths
    assert monitoring.saveEventScreenshot(None, 'players') is None
    assert not shots.exists()
