# frontend/tabs/rt_monitor_final.py
# Clean real-time monitor tab using the dedicated fast /api/rt/{slug} endpoint

import streamlit as st
import requests
import pandas as pd
import plotly.express as px
from datetime import datetime
import time

BACKEND_URL = "http://172.17.0.2:3001"

def render_rt_monitor_tab(surfaces):
    st.subheader("📡 Real-Time Monitor")

    if not surfaces:
        st.warning("No active surfaces loaded.")
        return

    slug = st.selectbox("Select Event", list(surfaces.keys()), key="rt_slug_final")
    auto = st.checkbox("Auto-refresh every 2 seconds", value=True, key="rt_auto_final")

    try:
        r = requests.get(f"{BACKEND_URL}/api/rt/{slug}", timeout=6)
        if r.status_code != 200:
            st.error(f"Backend error: {r.status_code}")
            return
        data = r.json()
    except Exception as e:
        st.error(f"Connection failed: {e}")
        return

    em = data.get("event_metrics") or {}

    # === Metrics row ===
    c1, c2, c3, c4 = st.columns(4)
    c1.metric("Yes Peak", f"{em.get('yes_peak', 0):.2f}")
    c2.metric("Overall Vol", f"{em.get('overall_volatility', 0):.2f}%")
    c3.metric("Direction", f"{em.get('overall_direction', 0):+.1f}%")
    c4.metric("Markets", data.get("market_count", 0))

    # === Per-market table ===
    st.markdown("**Per-Market (WS live)**")
    markets = em.get("markets", [])
    if markets:
        df = pd.DataFrame(markets)[["bin_label", "price", "volatility", "direction"]]
        df.columns = ["Bin", "Price", "Vol %", "Dir %"]
        st.dataframe(df, use_container_width=True, hide_index=True)
    else:
        st.info("Waiting for WebSocket data...")

    # === Recent ticks chart ===
    st.markdown("**Recent Price Ticks (last ~30 min)**")
    short = data.get("short_lived", {})
    if short:
        token = list(short.keys())[0]
        ticks = short[token]
        if ticks:
            df_t = pd.DataFrame(ticks)
            df_t["time"] = pd.to_datetime(df_t["t"], unit="s", utc=True).dt.tz_convert("Europe/Berlin")
            fig = px.line(df_t, x="time", y="p", title=token)
            st.plotly_chart(fig, use_container_width=True)

    st.caption(f"Updated: {datetime.now().strftime('%H:%M:%S')}")

    if auto:
        time.sleep(2)
        st.rerun()
