"""
events.py — nomes e helpers de eventos do TRM v1
"""

from typing import Dict, Any


# Eventos internos do TRM (nome simbólico)
TRM_EVENT_TEMP_RISING_FAST = "temp_rising_fast"
TRM_EVENT_ENTER_STRESS_ZONE = "enter_stress_zone"
TRM_EVENT_FS_WARNING = "fs_warning"
TRM_EVENT_LOOP_SUSPECT = "loop_suspect"
TRM_EVENT_RECOVERING = "recovering"


def summarize_telemetry_events(telemetry_events) -> Dict[str, int]:
    """
    Recebe a lista telemetry["events"] (strings) e devolve contagem por tipo.
    Exemplo:
        ["temp_rising_fast", "fs_warning", "fs_warning"]
    → { "temp_rising_fast": 1, "fs_warning": 2 }
    """
    counts: Dict[str, int] = {}
    if not telemetry_events:
        return counts

    for e in telemetry_events:
        if not isinstance(e, str):
            continue
        counts[e] = counts.get(e, 0) + 1
    return counts


def make_trm_snapshot_payload(state, tele) -> Dict[str, Any]:
    """
    Gera payload compacto para gravar no Hippocampus:
      kind="trm.snapshot"
      data = {...}
    """

    if tele is None:
        tele = {}

    raw = tele.get("raw", {}) or {}
    temp = tele.get("temp", 0.0)
    jitter = tele.get("jitter", 0.0)
    fs = tele.get("fs", {}) or {}
    events = tele.get("events", []) or []

    return {
        "state": state.to_dict(),
        "telemetry": {
            "cpu": raw.get("cpu"),
            "mem": raw.get("mem"),
            "load": raw.get("load"),
            "disk_delta": tele.get("delta", {}).get("disk"),
            "temp": temp,
            "jitter": jitter,
            "fs_read_only": fs.get("read_only"),
            "fs_free_percent": fs.get("free_percent"),
            "fs_io_errors": fs.get("io_errors"),
            "events": events,
        },
    }
