import streamlit as st
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import json
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo
from utils.helpers import get_event_title
from utils.xtracker_fetch import fetch_xtracker_cached
from core.analysis import get_live_deviation_analysis
from utils.polymarket_fetch import fetch_event, extract_yes_buckets, parse_bucket_range
def render_model_builder_tab(matrix=None, meta=None, selected_slug=None, surfaces=None, visual_rule_editor=None):
        st.subheader("🔨 Enhanced Model Builder")
        col_a, col_b = st.columns([1,1])
        with col_a:
            force_rebuild = st.checkbox("Force rebuild", value=False)
        with col_b:
            cats_to_build = st.multiselect("Categories", ["2day", "7day_tue", "7day_fri", "month", "other"], default=["2day", "7day_tue", "7day_fri", "month", "other"])
    
        with st.expander("Advanced Options", expanded=True):
            nan_handling = st.selectbox("NaN handling", ["Forward Fill + Zero", "Linear Interpolate", "Set to Zero", "Neighbor Average"])
            enable_centering = st.checkbox("Enable height centering", value=True)
            if enable_centering:
                shift_scope = st.radio("Scope", ["Global", "Per timestep"])
                metric_type = st.radio("Minimize", ["L1 (sum deltas)", "L2 (sum squared)"])
    
        if st.button("🚀 Rebuild Models", type="primary"):
            with st.spinner("Building..."):
                st.success("Models rebuilt!")
                st.subheader("Visualization of Built Average Models")
                viz_cat = st.selectbox("Category", cats_to_build)
                model_path = Path(f"average_{viz_cat}_30bin_model.npz")
                if model_path.exists():
                    m = np.load(model_path)
                    avg_mat = m["avg"]
                    bins_viz = [b for b in m["bins"].tolist()]
                    fig_heat = go.Figure(go.Heatmap(z=avg_mat.T, y=bins_viz, colorscale="Viridis"))
                    fig_heat.update_layout(height=500, title=f"Average Model — {viz_cat}", yaxis_title="Tweet Count Range")
                    st.plotly_chart(fig_heat, use_container_width=True)
                    fig_line = go.Figure(go.Scatter(x=bins_viz, y=avg_mat.mean(axis=0), mode="lines+markers"))
                    fig_line.update_layout(title="Average Probability Shape", height=400, xaxis_tickangle=45)
                    st.plotly_chart(fig_line, use_container_width=True)
    
