import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from geopy.distance import geodesic
import math
import time

st.set_page_config(page_title="CanSat Telemetry", layout="wide")
st.title("🛰️ Estación Terrena CanSat")

# Función para calcular velocidad lateral y dirección
def calcular_metricas_extra(df):
    # Convertir timestamp a objeto datetime
    df['Timestamp'] = pd.to_datetime(df['Timestamp'])
    df['TimeDiff'] = df['Timestamp'].diff().dt.total_seconds()

    # Velocidad vertical (Caída) basada en GPS (o BMP)
    df['Vel_Caida'] = df['AltGPS'].diff() / df['TimeDiff']

    lat_drift = []
    dir_drift = []

    for i in range(len(df)):
        if i == 0:
            lat_drift.append(0.0)
            dir_drift.append(0.0)
        else:
            p1 = (df['Lat'].iloc[i-1], df['Lon'].iloc[i-1])
            p2 = (df['Lat'].iloc[i], df['Lon'].iloc[i])
            # Evitar cálculos si no hay GPS válido (0.0, 0.0)
            if p1 == (0.0, 0.0) or p2 == (0.0, 0.0):
                lat_drift.append(0.0)
                dir_drift.append(0.0)
                continue

            # Distancia lateral (metros) y velocidad
            dist = geodesic(p1, p2).meters
            dt = df['TimeDiff'].iloc[i]
            vel = dist / dt if dt > 0 else 0
            lat_drift.append(vel)

            # Dirección (Bearing)
            lat1, lon1 = math.radians(p1[0]), math.radians(p1[1])
            lat2, lon2 = math.radians(p2[0]), math.radians(p2[1])
            dLon = lon2 - lon1
            y = math.sin(dLon) * math.cos(lat2)
            x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dLon)
            bearing = (math.degrees(math.atan2(y, x)) + 360) % 360
            dir_drift.append(bearing)

    df['Vel_Lateral'] = lat_drift
    df['Dir_Lateral'] = dir_drift
    return df

# Marcador de posición para recarga automática
placeholder = st.empty()

while True:
    try:
        df = pd.read_csv('cansat_data.csv')
        if len(df) > 1:
            df = calcular_metricas_extra(df)

            ultimo_dato = df.iloc[-1]

            with placeholder.container():
                # --- PANEL 1: Variables Numéricas ---
                st.subheader("1. Telemetría en Tiempo Real")
                c1, c2, c3, c4, c5 = st.columns(5)
                c1.metric("Tiempo", ultimo_dato['Timestamp'].strftime('%H:%M:%S'))
                c2.metric("Temperatura / Presión", f"{ultimo_dato['Temp']} °C / {ultimo_dato['Pres']} hPa")
                c3.metric("Altitud (BMP / GPS)", f"{ultimo_dato['AltBMP']:.1f} m / {ultimo_dato['AltGPS']:.1f} m")
                c4.metric("Vel. Caída (Vz)", f"{ultimo_dato['Vel_Caida']:.2f} m/s")
                c5.metric("Desplaz. Lateral (Vel / Dir)", f"{ultimo_dato['Vel_Lateral']:.2f} m/s | {ultimo_dato['Dir_Lateral']:.0f}°")

                st.write("---")

                # Gráficas
                col1, col2 = st.columns(2)

                # --- PANEL 2: Velocidad de Caída ---
                with col1:
                    st.subheader("2. Evolución de Velocidad de Caída")
                    fig_vel = px.line(df, x='Timestamp', y='Vel_Caida', title="Velocidad Vertical (m/s)")
                    st.plotly_chart(fig_vel, use_container_width=True)

                # --- PANEL 3: Altitud ---
                with col2:
                    st.subheader("3. Evolución de Altitud")
                    fig_alt = go.Figure()
                    fig_alt.add_trace(go.Scatter(x=df['Timestamp'], y=df['AltBMP'], mode='lines', name='Alt. BMP'))
                    fig_alt.add_trace(go.Scatter(x=df['Timestamp'], y=df['AltGPS'], mode='lines', name='Alt. GPS'))
                    st.plotly_chart(fig_alt, use_container_width=True)

                # --- PANEL 4: Mapa 2D ---
                st.subheader("4. Posición y Desplazamiento (GPS)")
                # Filtramos datos sin GPS válido para que el mapa no apunte al Golfo de Guinea (0,0)
                df_map = df[(df['Lat'] != 0.0) & (df['Lon'] != 0.0)]
                if not df_map.empty:
                    fig_map = px.line_mapbox(df_map, lat="Lat", lon="Lon", zoom=15, height=500)
                    fig_map.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
                    st.plotly_chart(fig_map, use_container_width=True)
                else:
                    st.info("Esperando fijación de satélites GPS...")

    except Exception as e:
        st.error(f"Esperando datos o error leyendo CSV: {e}")

    # Tasa de refresco de la pantalla (1 segundo)
    time.sleep(1)
