"""Anomalie-Monitoring: JSONL-Eventlog plus Beweis-Screenshots.

Failsafes, Session-Pausen und Hardware-Fehler werden mit Zeitstempel
protokolliert, damit Auffaelligkeiten nachvollziehbar bleiben, bevor daraus
ein Report wird. Das Log rotiert bei ~1 MB, Screenshots auf die letzten 5.

Config per Env:
  TIBIAPILOT_EVENTS_FILE      -> Pfad des Eventlogs
  TIBIAPILOT_EVENT_SHOT_DIR   -> Ordner fuer Beweis-Screenshots
"""
import json
import os
import time
from pathlib import Path

import cv2

EVENTS_FILE_ENV = 'TIBIAPILOT_EVENTS_FILE'
SHOT_DIR_ENV = 'TIBIAPILOT_EVENT_SHOT_DIR'
DEFAULT_EVENTS_FILE = '.pilotng-events.jsonl'
DEFAULT_SHOT_DIR = '.pilotng-events'
MAX_EVENTS_BYTES = 1024 * 1024
MAX_SHOTS = 5


def _eventsFile():
    return Path(os.getenv(EVENTS_FILE_ENV, DEFAULT_EVENTS_FILE))


def _shotDir():
    return Path(os.getenv(SHOT_DIR_ENV, DEFAULT_SHOT_DIR))


def logEvent(kind, details=None):
    path = _eventsFile()
    entry = {
        'at': time.strftime('%Y-%m-%dT%H:%M:%S'),
        'type': kind,
        'details': details or {},
    }
    try:
        if path.exists() and path.stat().st_size > MAX_EVENTS_BYTES:
            path.replace(path.with_name(path.name + '.old'))
        with path.open('a', encoding='utf-8') as handle:
            handle.write(json.dumps(entry) + '\n')
    except OSError:
        pass


def saveEventScreenshot(screenshot, label):
    if screenshot is None:
        return None
    try:
        directory = _shotDir()
        directory.mkdir(exist_ok=True)
        target = directory / f'{int(time.time())}-{label}.png'
        cv2.imwrite(str(target), screenshot)
        shots = sorted(directory.glob('*.png'))
        for old in shots[:-MAX_SHOTS]:
            old.unlink()
        return str(target)
    except OSError:
        return None
