"""Forecast — projects a metric forward with trend and seasonality, shows the
uncertainty band, how accurate the model was recently, and unusual periods."""

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st

st.set_page_config(page_title="Forecast", layout="wide")

# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True runs on generated sample data. To use your own table, set
# DEMO = False and make the query return these columns (rename with AS):
# one row per date (and segment) with the value to forecast.
DEMO = True
SERIES_SQL = """
SELECT DATE, SEGMENT, VALUE
FROM {{DATABASE}}.{{SCHEMA}}.DAILY_METRIC
"""
METRIC_NAME = "Orders"
# ──────────────────────────────────────────────────────────────────────────────


def demo_series() -> pd.DataFrame:
    rng = np.random.default_rng(29)
    days = pd.date_range(end=pd.Timestamp.today().normalize(), periods=3 * 365, freq="D")
    t = np.arange(len(days))
    rows = []
    for seg, base, growth in (("Online", 420, 0.0009), ("Retail", 300, 0.0003), ("Wholesale", 120, 0.0006)):
        yearly = 1 + 0.18 * np.sin((days.dayofyear.to_numpy() - 80) / 365 * 2 * np.pi)
        weekly = np.where(days.dayofweek.to_numpy() >= 5, 0.75, 1.05)
        y = base * (1 + growth * t) * yearly * weekly * rng.normal(1, 0.06, len(days))
        spikes = rng.random(len(days)) < 0.006
        y[spikes] *= rng.uniform(1.6, 2.2, spikes.sum())
        rows.append(pd.DataFrame({"DATE": days, "SEGMENT": seg, "VALUE": y.round()}))
    return pd.concat(rows, ignore_index=True)


@st.cache_data(ttl=600, show_spinner=False)
def load_series() -> pd.DataFrame:
    if DEMO:
        df = demo_series()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(SERIES_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    df["DATE"] = pd.to_datetime(df["DATE"], errors="coerce")
    df["VALUE"] = pd.to_numeric(df["VALUE"], errors="coerce")
    df["SEGMENT"] = df["SEGMENT"].fillna("All").astype(str) if "SEGMENT" in df else "All"
    return df.dropna(subset=["DATE", "VALUE"])


def design(index: pd.DatetimeIndex, start: pd.Timestamp, grain: str) -> np.ndarray:
    """Trend + seasonal dummies (month of year for monthly, week of year buckets for weekly)."""
    t = ((index - start).days / 365.25).to_numpy()
    season = index.month.to_numpy() if grain == "Month" else ((index.isocalendar().week.to_numpy() - 1) // 4 + 1).clip(1, 13)
    k = 12 if grain == "Month" else 13
    dummies = np.eye(k)[season - 1][:, 1:]
    return np.column_stack([np.ones(len(index)), t, dummies])


def fit_forecast(y: pd.Series, grain: str, horizon: int):
    start = y.index[0]
    X = design(y.index, start, grain)
    coef, *_ = np.linalg.lstsq(X, y.to_numpy(), rcond=None)
    fitted = pd.Series(X @ coef, index=y.index)
    resid = y - fitted
    freq = "MS" if grain == "Month" else "W-MON"
    future = pd.date_range(y.index[-1], periods=horizon + 1, freq=freq)[1:]
    pred = pd.Series(design(future, start, grain) @ coef, index=future)
    sigma = resid.std(ddof=X.shape[1]) if len(y) > X.shape[1] else resid.std()
    return fitted, pred, sigma, resid


st.title(f"{METRIC_NAME} forecast")
if DEMO:
    st.caption("Showing generated demo data — connect your own table in the DATA section.")

try:
    series = load_series()
except Exception as e:
    st.error(f"Could not load the series: {e}")
    st.stop()
if series.empty:
    st.info("No data yet.")
    st.stop()

with st.sidebar:
    st.header("Settings")
    segments = sorted(series["SEGMENT"].unique())
    chosen = st.multiselect("Segment", segments, default=segments)
    grain = st.radio("Grain", ["Week", "Month"], horizontal=True)
    horizon = st.slider("Periods ahead", 4, 26 if grain == "Week" else 18, 12 if grain == "Week" else 6)

scoped = series[series["SEGMENT"].isin(chosen)] if chosen else series
rule = "W-MON" if grain == "Week" else "MS"
y = scoped.set_index("DATE")["VALUE"].resample(rule, label="left", closed="left").sum()
y = y.iloc[1:-1] if len(y) > 3 else y      # drop partial first/last periods
min_periods = 30 if grain == "Week" else 18
if len(y) < min_periods:
    st.info(f"Need at least {min_periods} {grain.lower()}s of history for a forecast (have {len(y)}).")
    st.stop()

fitted, pred, sigma, resid = fit_forecast(y, grain, horizon)

# Backtest: refit without the last `horizon` periods and compare.
hold = min(horizon, len(y) // 4)
_, back, _, _ = fit_forecast(y.iloc[:-hold], grain, hold)
actual = y.iloc[-hold:]
mape = (abs(back.to_numpy() - actual.to_numpy()) / actual.replace(0, np.nan).to_numpy())
mape = np.nanmean(mape)

z = resid / resid.std() if resid.std() else resid * 0
anomalies = y[abs(z) > 2.5]

k = st.columns(4)
k[0].metric(f"Next {horizon} {grain.lower()}s", f"{pred.sum():,.0f}")
k[1].metric(f"Last {horizon} {grain.lower()}s", f"{y.iloc[-horizon:].sum():,.0f}",
            f"{pred.sum() / y.iloc[-horizon:].sum() - 1:+.1%} ahead" if y.iloc[-horizon:].sum() else None)
k[2].metric("Recent accuracy", f"{1 - mape:.0%}" if np.isfinite(mape) else "–", help=f"1 − mean absolute % error over the last {hold} periods, forecast without them")
k[3].metric("Unusual periods", f"{len(anomalies)}")

band = 1.64 * sigma   # ~90% interval
fig = go.Figure()
fig.add_scatter(x=y.index, y=y, name="Actual", line=dict(color="#4c78a8"))
fig.add_scatter(x=fitted.index, y=fitted, name="Model", line=dict(color="#9ecae9", dash="dot"))
fig.add_scatter(x=list(pred.index) + list(pred.index[::-1]), y=list(pred + band) + list((pred - band)[::-1]),
                fill="toself", fillcolor="rgba(245,133,24,0.18)", line=dict(width=0), name="90% range", hoverinfo="skip")
fig.add_scatter(x=pred.index, y=pred, name="Forecast", line=dict(color="#f58518", width=3))
fig.add_scatter(x=anomalies.index, y=anomalies, mode="markers", name="Unusual", marker=dict(color="#d62728", size=9, symbol="x"))
fig.update_layout(title=f"{METRIC_NAME} by {grain.lower()}", legend_title_text="", margin=dict(t=50, b=10), hovermode="x unified")
st.plotly_chart(fig, width="stretch")
st.caption("Model: linear trend plus seasonality, fitted in the app. For production forecasting at scale, "
           "Snowflake's SNOWFLAKE.ML.FORECAST can replace it.")

left, right = st.columns(2)
left.subheader("Forecast")
left.dataframe(pd.DataFrame({"PERIOD": pred.index, "FORECAST": pred.round(), "LOW": (pred - band).round(), "HIGH": (pred + band).round()}),
               width="stretch", column_config={"PERIOD": st.column_config.DateColumn("Period")})
right.subheader("Unusual periods")
if anomalies.empty:
    right.success("Nothing unusual in the history.")
else:
    right.dataframe(pd.DataFrame({"PERIOD": anomalies.index, "ACTUAL": anomalies.round(), "EXPECTED": fitted[anomalies.index].round()})
                    .sort_values("PERIOD", ascending=False).reset_index(drop=True),
                    width="stretch", column_config={"PERIOD": st.column_config.DateColumn("Period")})
