import os
import streamlit as st
import requests
import pandas as pd
import plotly.graph_objects as go

# ---- API ----
API_BASE = os.environ.get("API_BASE", "http://backend:8000")

st.set_page_config(page_title="Market Regime", layout="wide")
st.title("Market regime & buy advice")

# ---- Get assets from API ----
def get_assets():
    try:
        response = requests.get(f"{API_BASE}/assets")
        response.raise_for_status()
        return response.json().get("assets", [])
    except Exception as e:
        st.error(f"Failed to fetch assets: {e}")
        return []

assets = get_assets()

if not assets:
    st.warning("No assets found. Make sure backend is running and data exists.")
    st.stop()

asset = st.sidebar.selectbox("Choose asset", options=assets)

# ---- Get chart data ----
def get_chart_data(asset):
    try:
        response = requests.get(f"{API_BASE}/data/{asset}/chart")
        response.raise_for_status()
        return pd.DataFrame(response.json())
    except Exception as e:
        st.error(f"Could not load chart data: {e}")
        return None

df = get_chart_data(asset)

if df is None or df.empty:
    st.stop()

df["date"] = pd.to_datetime(df["date"])

# ---- Regime colors ----
regime_color = {
    "bull": "#22c55e",
    "bear": "#ef4444",
    "sideways": "#eab308"
}

# ---- Ensure hover text color ----
if "hover_text_color" not in df.columns:
    df["hover_text_color"] = "white"

# ---- Plot ----
fig = go.Figure()

# Price line
fig.add_trace(
    go.Scatter(
        x=df["date"],
        y=df["close"],
        mode="lines",
        name="Close",
        line=dict(color="#0ea5e9", width=2),
    )
)

# Regime overlay (colored dots)
fig.add_trace(
    go.Scatter(
        x=df["date"],
        y=df["close"],
        mode="markers",
        name="Regime",
        customdata=df[["regime_label", "hover_text_color"]],
        marker=dict(
            size=5,
            color=df["regime_label"].map(regime_color).fillna("#94a3b8"),
            opacity=0.5,
            line=dict(width=0),
        ),
        hovertemplate=(
            "<b><span style='color: white;'>Regime:</span></b> "
            "<b><span style='color: %{customdata[1]};'>%{customdata[0]}</span></b><br>"
            "Date: %{x|%Y-%m-%d}<br>"
            "Close: %{y}<extra></extra>"
        ),
    )
)

fig.update_layout(
    title=f"{asset} — Price & regime",
    xaxis_title="Date",
    yaxis_title="Close",
    template="plotly_dark",
    height=500,
    legend=dict(orientation="h", yanchor="bottom", y=1.02),
)

st.plotly_chart(fig, use_container_width=True)

# ---- Get current regime ----
def get_current_regime(asset):
    try:
        response = requests.get(f"{API_BASE}/regime/{asset}")
        response.raise_for_status()
        return response.json()
    except Exception as e:
        st.error(f"Failed to fetch regime info: {e}")
        return None

regime_info = get_current_regime(asset)

if regime_info:
    current_regime = regime_info["regime_label"]

    col1, col2, col3 = st.columns(3)

    with col1:
        st.metric("Current regime", current_regime.capitalize())

    with col2:
        if current_regime == "bull":
            st.success("Favorable for long bias (bull)")
        elif current_regime == "bear":
            st.error("Caution for new longs (bear)")
        else:  # sideways
            st.info("Neutral market (sideways)")

    with col3:
        st.caption("Advice")
        st.write(regime_info.get("advice", ""))

st.caption("This is not financial advice. For educational purposes only.")