import streamlit as st
import pandas as pd
import os
import time
from datetime import datetime
import requests
import paho.mqtt.client as mqtt
import psutil  # AGGIUNTO per monitoraggio processi

def is_main_running():
    """Verifica se il processo main.py è attualmente in esecuzione."""
    for proc in psutil.process_iter(['cmdline']):
        try:
            cmd = proc.info['cmdline']
            if cmd and 'app.main' in ' '.join(cmd):
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
    return False


def check_mqtt_broker(host, port, protocol_str="mqttv311"):
    try:
        # Mappatura protocollo per compatibilità paho-mqtt
        proto = mqtt.MQTTv311
        if protocol_str == "mqttv5":
            proto = mqtt.MQTTv5
            
        client = mqtt.Client(protocol=proto)
        # Aumentiamo il timeout a 5 secondi per maggiore stabilità
        client.connect(host, port, keepalive=5)
        client.disconnect()
        return True
    except Exception as e:
        # Utile per il debug interno se necessario
        return False

def check_api_server(token_url, verify_tls):
    try:
        response = requests.get(token_url, timeout=2, verify=verify_tls)
        return True
    except:
        return False

def show_system_status(cfg, secrets):
    st.subheader("🖥️ Stato Infrastruttura")
    
    col1, col2, col3, col4 = st.columns(4)
    
    # 1. CORE ENGINE
    main_active = is_main_running()
    col1.metric("Core Engine", "ON" if main_active else "OFF", 
                delta=None, delta_color="normal")
    if main_active: col1.success("✅ Main Attivo")
    else: col1.error("❌ Main Fermo")

    # 2. MQTT BROKER
    mqtt_cfg = cfg.get('mqtt', {})
    mqtt_ok = check_mqtt_broker(
        mqtt_cfg.get('host', 'localhost'), 
        mqtt_cfg.get('port', 1883),
        mqtt_cfg.get('protocol', 'mqttv311')
    )
    col2.metric("MQTT Broker", "Online" if mqtt_ok else "Offline")
    if mqtt_ok: col2.success("✅ Broker OK")
    else: col2.error("❌ Errore MQTT")

    # 3. API SERVER
    api_cfg = cfg.get('api', {})
    api_ok = check_api_server(api_cfg.get('token_url', ''), api_cfg.get('verify_tls', False))
    col3.metric("API System", "Ready" if api_ok else "Error")
    if api_ok: col3.success("✅ API OK")
    else: col3.error("❌ API Down")

    # 4. DISCO (Data Dir)
    try:
        usage = psutil.disk_usage('/data')
        col4.metric("Spazio Disco", f"{usage.percent}%")
        if usage.percent < 90: col4.success(f"✅ {usage.free // (1024**3)} GB Liberi")
        else: col4.warning("⚠️ Disco quasi pieno")
    except:
        col4.write("N/D")

    # LOG RECENTI (Ripristinati dal tuo originale)
    st.divider()
    st.subheader("📝 Ultimi Eventi Log")
    LOG_FILE = "/tmp/main_process.log"
    if os.path.exists(LOG_FILE):
        with open(LOG_FILE, "r") as f:
            lines = f.readlines()
            st.text_area("Log in tempo reale:", "".join(lines[-20:]), height=300)
    else:
        st.info("Nessun file di log trovato in /tmp/main_process.log")
