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_data_updater_tab(matrix=None, meta=None, selected_slug=None, surfaces=None, visual_rule_editor=None):
        st.subheader("🔄 Data Updater")
        if st.button("📋 Show Exact Curl Commands for this Event", type="primary"):
            st.code(f"""curl -s "https://gamma.api.polymarket.com/markets?slug={selected_slug}" | jq '.'
    curl -s "https://clob.polymarket.com/prices-history?market=PASTE_TOKEN_ID_HERE&fidelity=30&startTs=1737763200" | jq '.'""", language="bash")
    
        if st.button("🛠️ FORCE FULL HISTORY REFRESH (all active events)", type="primary"):
            with st.spinner("Trying full history refresh..."):
                try:
                    resp = requests.get(f"https://gamma-api.polymarket.com/events?slug={selected_slug}")
                    event = resp.json()[0] if isinstance(resp.json(), list) else resp.json()
                    markets = event["markets"]
                    buckets = extract_yes_buckets(event)
                    tokens = [b['token'] for b in buckets]
                    all_timestamps = set()
                    price_dict = {}
                    for token in tokens:
                        if not token:
                            continue
                        r = requests.get(
                                f"https://clob.polymarket.com/prices-history?market={token}&startTs={int(time.mktime(datetime.fromisoformat(event["startDate"].split("T")[0]).timetuple()))}&endTs={int(time.time())}&fidelity=30"
                        )
                        history = r.json()
                        if not history:
                            continue
                        times = [p["t"] for p in history["history"]]
                        prices = [p["p"] for p in history["history"]]
                        all_timestamps.update(times)
                        price_dict[token] = dict(zip(times, prices))
    
                    if not all_timestamps:
                        st.error("No data received from API")
                    else:
                        full_ts = sorted(all_timestamps)
                        full_matrix = []
                        for token in tokens:
                            token_id = token
                            if token_id not in price_dict:
                                full_matrix.append([0] * len(full_ts))
                                continue
                            row = [price_dict[token_id].get(t, np.nan) for t in full_ts]
                            full_matrix.append(row)
    
                        full_matrix = np.array(full_matrix).T
                        df = pd.DataFrame(full_matrix)
                        df = df.ffill().bfill().fillna(0)
                        full_matrix = df.values
    
                        out_file = OUTPUT_DIR / f"elon_surface_{selected_slug}_FULL.npz"
                        if out_file.exists():
                            try:
                                os.remove(out_file)
                                print(f"File '{out_file}' deleted successfully.")
                            except:
                                print(f"unable to delete '{out_file}'.")
    
                        meta = {
                            "event_slug": selected_slug,
                            "event_title": event.get("title") or event.get("question", selected_slug),
                            "start_date": event["startDate"],
                            "end_date": event["endDate"],
                            "bins": [b["label"] for b in buckets],
                            "timestamps": full_ts,
                            "fidelity_min": FIDELITY,
                            "num_bins": len(buckets)
                        }
                        np.savez_compressed(out_file, matrix=full_matrix, **meta)
                        print(f"   ✅ SAVED — {len(full_ts)} ts × {len(buckets)} bins")
                except Exception as e:
                    st.error(f"API call failed: {e}")
                    st.info("Use the 'Show Exact Curl Commands' button above and run them in your terminal.")
    
        auto_update = st.checkbox("Auto-update recent data every 5 min", value=False)
        if auto_update and time.time() - st.session_state.get('last_auto', 0) > 300:
            st.session_state.last_auto = time.time()
            st.rerun()
    
