#!/usr/bin/env python3
"""
📊 Painel de Telemetria do Neurotron — V0.1
Lê o ficheiro telemetry.json e mostra um mini-ECG digital:
 ▂▃▄▅▆▇█

Execução:
    python3 /opt/kernel/neurotron/neurotron_core/telemetry_tail.py
"""

import json
import time
import os
from pathlib import Path
from statistics import mean
from rich.console import Console
from rich.table import Table
from rich.panel import Panel

DATASET = "/opt/kernel/neurotron/data/telemetry.json"
BAR_CHARS = "▁▂▃▄▅▆▇█"
SAMPLES = 24  # quantas amostras recentes mostrar
REFRESH = 2.0  # segundos entre atualizações


def mini_graph(values, width=24):
    """Desenha barras simples tipo sparkline"""
    if not values:
        return "·" * width
    vals = [v for v in values if isinstance(v, (int, float))]
    if not vals:
        return "·" * width
    lo, hi = min(vals), max(vals)
    span = (hi - lo) or 1.0
    bars = []
    for v in vals[-width:]:
        if not isinstance(v, (int, float)):
            bars.append("·")
            continue
        i = int(round((v - lo) / span * (len(BAR_CHARS) - 1)))
        bars.append(BAR_CHARS[i])
    return "".join(bars)


def read_telemetry(path: str):
    try:
        data = json.loads(Path(path).read_text() or "[]")
        return data[-SAMPLES:]
    except Exception:
        return []


def render_panel(console, data):
    if not data:
        console.print("[yellow]Nenhum dado de telemetria disponível.[/yellow]")
        return

    cpu = [d.get("cpu") for d in data if isinstance(d.get("cpu"), (int, float))]
    mem = [d.get("mem") for d in data if isinstance(d.get("mem"), (int, float))]
    load = [d.get("load")[0] for d in data if isinstance(d.get("load"), (list, tuple)) and isinstance(d.get("load")[0], (int, float))]

    table = Table(show_header=True, header_style="bold cyan")
    table.add_column("Sinal Vital", justify="left")
    table.add_column("Tendência", justify="left")
    table.add_column("Média", justify="right")

    table.add_row("CPU (%)", mini_graph(cpu), f"{mean(cpu):.1f}%" if cpu else "?")
    table.add_row("Memória (%)", mini_graph(mem), f"{mean(mem):.1f}%" if mem else "?")
    table.add_row("Carga (1min)", mini_graph(load), f"{mean(load):.2f}" if load else "?")

    panel = Panel(table, title="🩺 TELEMETRIA RECENTE", border_style="green")
    console.clear()
    console.print(panel)


def main():
    console = Console()
    console.print("[bold cyan]Neurotron Telemetry Tail — Iniciar Monitorização[/bold cyan]\n")

    while True:
        if not Path(DATASET).exists():
            console.print(f"[yellow]A aguardar dados em {DATASET}...[/yellow]")
            time.sleep(REFRESH)
            continue

        data = read_telemetry(DATASET)
        if not data:
            console.print("[yellow]Nenhum dado de telemetria disponível.[/yellow]")
        else:
            render_panel(console, data)
        time.sleep(REFRESH)


if __name__ == "__main__":
    main()
