import streamlit as st
import pandas as pd
import os
import json
import folium
from streamlit_folium import st_folium
from pathlib import Path
from PIL import Image
import base64
from io import BytesIO

# --- UTILS ---
@st.cache_data
def get_image_base64(img_path):
    img = Image.open(img_path).convert("RGBA")
    w, h = img.size
    buffered = BytesIO()
    img.save(buffered, format="PNG")
    img_str = base64.b64encode(buffered.getvalue()).decode("ascii")
    return f"data:image/png;base64,{img_str}", w, h

def show_inference_page(cfg):
    st.subheader("📡 Monitoraggio Beacon Real-Time")
    
    # --- CONFIGURAZIONE PERCORSI ---
    MAPS_DIR = Path(cfg['maps']['map_dir'])
    INFER_FILE = Path("/data/infer/infer.csv")
    
    # --- 1. SELEZIONE E STATO (RIGA COMPATTA) ---
    maps = sorted([f.replace(cfg['maps']['floor_prefix'], "").split('.')[0] 
                   for f in os.listdir(MAPS_DIR) if f.startswith(cfg['maps']['floor_prefix'])])
    
    if not maps:
        st.warning("Nessuna mappa configurata.")
        return

    # Lettura dati per conteggio
    df_infer = pd.DataFrame()
    if INFER_FILE.exists():
        df_infer = pd.read_csv(INFER_FILE, sep=";")

    # Layout riga 1
    c_piano, c_count, c_size = st.columns([3, 2, 2])
    
    with c_piano:
        sub1, sub2 = st.columns([1, 1.2])
        sub1.markdown("<p style='padding-top:35px; font-weight:bold; font-size:15px;'>Piano Visualizzato:</p>", unsafe_allow_html=True)
        floor_id = sub2.selectbox("", maps, key="inf_floor_v24", label_visibility="collapsed")
    
    # Filtro dati per il piano scelto
    df_active = df_infer[(df_infer['z'].astype(str) == str(floor_id)) & (df_infer['x'] != -1)] if not df_infer.empty else pd.DataFrame()

    with c_count:
        st.info(f"📡 Beacon Attivi: **{len(df_active)}**\n(Totali nel file: {len(df_infer)})")

    with c_size:
        # Slider per dimensione pallini (come nel mapper)
        m_size = st.slider("Dimensione Beacon:", 5, 20, 8, key="inf_msize_v24")

    # Caricamento Metadati
    meta_path = MAPS_DIR / f"{cfg['maps']['meta_prefix']}{floor_id}.json"
    if not meta_path.exists(): return
    with open(meta_path, "r") as f: meta = json.load(f)

    # --- 2. RENDERING MAPPA ---
    st.markdown("---")
    img_p = next((MAPS_DIR / f"{cfg['maps']['floor_prefix']}{floor_id}{e}" for e in ['.png','.jpg'] if (MAPS_DIR / f"{cfg['maps']['floor_prefix']}{floor_id}{e}").exists()))
    img_data, w, h = get_image_base64(img_p)
    bounds = [[0, 0], [h, w]]
    
    m = folium.Map(location=[h/2, w/2], crs="Simple", tiles=None, attribution_control=False)
    m.fit_bounds(bounds)
    m.options.update({"minZoom": -6, "maxZoom": 6, "zoomSnap": 0.25, "maxBounds": bounds, "maxBoundsViscosity": 1.0})
    folium.raster_layers.ImageOverlay(image=img_data, bounds=bounds).add_to(m)

    # Disegno Beacon
    if meta["calibrated"] and meta["origin"] != [0,0]:
        # Origine
        folium.CircleMarker(location=[meta["origin"][1], meta["origin"][0]], radius=4, color="black", fill=True).add_to(m)

        for _, row in df_active.iterrows():
            px_x = (row['x'] * meta["pixel_ratio"]) + meta["origin"][0]
            px_y = meta["origin"][1] - (row['y'] * meta["pixel_ratio"])
            mac_label = str(row['mac'])[-5:]

            folium.CircleMarker(
                location=[px_y, px_x], radius=m_size, color="blue", 
                fill=True, fill_color="cyan", fill_opacity=0.8
            ).add_to(m)

            folium.Marker(
                location=[px_y, px_x],
                icon=folium.DivIcon(html=f"""<div style="font-family: sans-serif; color: black; font-weight: bold; font-size: {int(m_size*1.2)}pt; width: 80px; transform: translate({m_size+2}px, -{m_size+2}px);">{mac_label}</div>""")
            ).add_to(m)

    st_folium(m, height=700, width=None, key=f"inf_map_v24_{floor_id}", use_container_width=True)

    # --- 3. TABELLA RIEPILOGO COMPLETA ---
    if not df_infer.empty:
        st.subheader("Dettaglio Dispositivi (Tutti i Piani)")
        # Aggiunta colonna Z per chiarezza
        st.dataframe(df_infer[['mac', 'z', 'x', 'y']], use_container_width=True)
