import json
from datetime import datetime
from pathlib import Path

import pandas as pd
import streamlit as st

LOG_PATH = Path("/var/www/ouilogique/public/mqtt-mailbox-rolf.log")


def parse_log_file(log_path: Path) -> pd.DataFrame:
    rows = []

    if not log_path.exists():
        return pd.DataFrame()

    with log_path.open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue

            parts = line.split("\t", 2)
            if len(parts) < 3:
                continue

            timestamp_str, _, payload_str = parts

            if "HEARTBEAT" in payload_str:
                continue

            try:
                payload = json.loads(payload_str)
                timestamp = datetime.strptime(timestamp_str, "%Y-%m-%dT%H:%M:%S%z")
            except (json.JSONDecodeError, ValueError):
                continue

            rows.append(
                {
                    "time": timestamp,
                    "RSSI (dBm)": payload.get("RSSI (dBm)"),
                    "SNR (dB)": payload.get("SNR (dB)"),
                    "COUNTER ERROR COUNT": payload.get("COUNTER", {}).get("ERROR COUNT"),
                }
            )

    if not rows:
        return pd.DataFrame()

    df = pd.DataFrame(rows).set_index("time").sort_index()
    return df


st.set_page_config(page_title="MQTT Mailbox", layout="wide")
st.title("MQTT Mailbox Metrics")

if st.button("Charger et afficher le graphique"):
    df = parse_log_file(LOG_PATH)

    if df.empty:
        st.warning("Aucune donnée exploitable trouvée dans le log.")
    else:
        st.line_chart(df[["RSSI (dBm)", "SNR (dB)", "COUNTER ERROR COUNT"]])
        st.dataframe(df.tail(50), use_container_width=True)

st.caption(f"Fichier log: {LOG_PATH}")
