import streamlit as st
import yaml
import subprocess
import os
import time
import signal
import web_status 
import psutil

# --- 1. CONFIGURAZIONE PAGINA ---
st.set_page_config(
    page_title="BLE Localizer Manager",
    layout="wide",
    initial_sidebar_state="auto"
)

# --- 2. CONFIGURAZIONE PERCORSI ---
REAL_CONFIG_PATH = "/config/config.yaml"
if not os.path.exists(REAL_CONFIG_PATH):
    REAL_CONFIG_PATH = "/app/config/config.yaml"

LOG_FILE = "/tmp/main_process.log"

def load_yaml(path):
    if not os.path.exists(path): return {}
    with open(path, 'r', encoding='utf-8') as f: return yaml.safe_load(f) or {}

def save_yaml(path, data):
    with open(path, 'w', encoding='utf-8') as f: yaml.dump(data, f, default_flow_style=False)

cfg = load_yaml(REAL_CONFIG_PATH)

def stop_core_engine():
    for proc in psutil.process_iter(['cmdline']):
        try:
            cmd = proc.info['cmdline']
            if cmd and ('app.main' in ' '.join(cmd) or 'main.py' in ' '.join(cmd)):
                proc.terminate()
                proc.wait(timeout=2)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
            try: proc.kill()
            except: pass

def start_core_engine():
    env = os.environ.copy()
    env["CONFIG"] = REAL_CONFIG_PATH 
    env["PYTHONPATH"] = "/app"
    with open(LOG_FILE, "a") as log_f:
        subprocess.Popen(
            ["python3", "-m", "app.main"],
            env=env,
            cwd="/app",
            stdout=log_f,
            stderr=log_f,
            start_new_session=True
        )

# --- 3. TITOLO FISSO ---
st.title("🛰️ BLE AI Localizer - Suite")

# --- 4. LOGICA LOGIN ---
if "password_correct" not in st.session_state:
    st.session_state["password_correct"] = False

if not st.session_state["password_correct"]:
    user = st.text_input("Username")
    pw = st.text_input("Password", type="password")
    if st.button("ACCEDI"):
        if user == os.environ.get("UI_USER", "admin") and pw == os.environ.get("UI_PASSWORD", "password"):
            st.session_state["password_correct"] = True
            st.rerun()
        else:
            st.error("Credenziali errate")
    st.stop()

# --- 5. AUTO-START ---
if not web_status.is_main_running():
    if "core_auto_launched" not in st.session_state:
        start_core_engine()
        st.session_state["core_auto_launched"] = True
        time.sleep(1) 
        st.rerun()

# --- 6. SIDEBAR: CONTROLLI SISTEMA ---
with st.sidebar:
    st.header("🛠️ Core Control")
    
    is_running = web_status.is_main_running()
    if is_running:
        st.markdown("STATO: :green[**CORE ATTIVO**]")
    else:
        st.markdown("STATO: :red[**CORE FERMO**]")
    
    if st.button("🚀 RIAVVIA CORE" if is_running else "▶️ AVVIA CORE", use_container_width=True):
        with st.spinner("Gestione Core..."):
            stop_core_engine()
            time.sleep(1)
            start_core_engine()
            time.sleep(2)
            st.rerun()

    st.divider()
    # --- GESTIONE MQTT RAW (DINAMICA DA CONFIG) ---
    m_cfg = cfg.get('mqtt', {})
    m_host = m_cfg.get('host', '127.0.0.1')
    m_port = m_cfg.get('port', 1883)
    m_proto = m_cfg.get('protocol', 'mqttv311')
    # Estraiamo la parola chiave dal topic (es: 'publish_out' da 'publish_out/#')
    m_filter = m_cfg.get('topic', 'publish_out').split('/')[0]

    RAW_LOG_DIR = cfg.get('paths', {}).get('mqtt_raw_dir', '/data/mqtt_raw/')
    os.makedirs(RAW_LOG_DIR, exist_ok=True)
    raw_active = st.toggle("🔴 MQTT RAW RECORDING", value=st.session_state.get("mqtt_logging", False))
    
    if raw_active and not st.session_state.get("mqtt_logging"):
        dt = time.strftime("%Y%m%d_%H%M%S")
        filepath = os.path.join(RAW_LOG_DIR, f"mqtt_raw_{dt}.log")
        
        # Comando generato dinamicamente dai parametri YAML
        cmd = f"stdbuf -oL mosquitto_sub -v -h {m_host} -p {m_port} -t '#' -V {m_proto} | stdbuf -oL grep '{m_filter}' > {filepath}"
        
        proc = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
        st.session_state["mqtt_logging"] = True
        st.session_state["mqtt_proc_pid"] = proc.pid
        st.success(f"Log avviato: {m_host}")
    
    if not raw_active and st.session_state.get("mqtt_logging"):
        try: 
            os.killpg(os.getpgid(st.session_state["mqtt_proc_pid"]), signal.SIGTERM)
        except: 
            pass
        st.session_state["mqtt_logging"] = False

# --- 7. IMPORT MODULI E TABS ---
from map_manager import show_mapper
from web_gateway import show_gateway_manager
from web_beacon import show_beacon_manager
from web_test_inference import show_test_inference
import web_training_data
import web_inference

tab_log, tab_cfg, tab_sec, tab_gw, tab_beac, tab_map, tab_model, tab_infer_test, tab_infer, tab_status = st.tabs([
    "📜 Log", "⚙️ Config", "🔑 Secrets", "🌐 Gateway", "🏷️ Beacon", "📍 Rilevamento", "🧠 Modello", "🧪 InferTest", "🤖 Inferenza", "🖥️ Stato"
])

with tab_log:
    col_l1, col_l2 = st.columns(2)
    if col_l1.button("🔄 AGGIORNA LOG", use_container_width=True): st.rerun()
    if col_l2.button("🗑️ AZZERA LOG", use_container_width=True):
        try:
            with open(LOG_FILE, "w") as f: f.write(f"--- Log resettato il {time.strftime('%Y-%m-%d %H:%M:%S')} ---\n")
            st.success("Log azzerato!"); time.sleep(1); st.rerun()
        except: st.error("Errore pulizia log")
    if os.path.exists(LOG_FILE):
        with open(LOG_FILE, "r") as f: st.code("".join(f.readlines()[-100:]))

with tab_cfg:
    st.subheader("🚀 Configurazione Operativa")
    cfg_text = st.text_area("Expert Mode (YAML)", yaml.dump(cfg), height=400)
    if st.button("💾 SALVA CONFIG"):
        save_yaml(REAL_CONFIG_PATH, yaml.safe_load(cfg_text)); st.success("Salvato!")

with tab_sec:
    CURR_SECRETS = os.environ.get("SECRETS_FILE") or "/config/secrets.yaml"
    sec = load_yaml(CURR_SECRETS)
    sec_edit = st.text_area("Secrets YAML", yaml.dump(sec), height=200)
    if st.button("SALVA SECRETS"): 
        save_yaml(CURR_SECRETS, yaml.safe_load(sec_edit)); st.success("OK!")

with tab_gw: show_gateway_manager(cfg)
with tab_beac: show_beacon_manager(cfg)
with tab_map: show_mapper(cfg)
with tab_model: web_training_data.show_training_data_manager(cfg)
with tab_infer_test: show_test_inference(cfg) 
with tab_infer: web_inference.show_inference_page(cfg)
with tab_status:
    sec_data = load_yaml(os.environ.get("SECRETS_FILE") or "/config/secrets.yaml")
    web_status.show_system_status(cfg, sec_data)
