"""Budget vs actual — spend against budget by department and category, with
variances, year-to-date burn and the lines that need attention."""

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

st.set_page_config(page_title="Budget vs actual", 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).
DEMO = True
BUDGET_SQL = """
SELECT PERIOD, DEPARTMENT, CATEGORY, BUDGET, ACTUAL
FROM {{DATABASE}}.{{SCHEMA}}.BUDGET_ACTUALS
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = px.colors.qualitative.Safe
TOLERANCE = 0.05   # over budget by more than this share → flagged


def demo_budget() -> pd.DataFrame:
    rng = np.random.default_rng(5)
    year = pd.Timestamp.today().year
    months = pd.date_range(f"{year}-01-01", periods=12, freq="MS")
    today = pd.Timestamp.today().normalize()
    plan = {
        "Sales": {"Salaries": 120_000, "Travel": 18_000, "Software": 9_000, "Events": 12_000},
        "Marketing": {"Salaries": 70_000, "Campaigns": 55_000, "Software": 14_000, "Events": 20_000},
        "R&D": {"Salaries": 210_000, "Cloud": 45_000, "Software": 22_000, "Contractors": 30_000},
        "Operations": {"Salaries": 90_000, "Facilities": 40_000, "Software": 8_000, "Logistics": 35_000},
    }
    rows = []
    for m in months:
        for dept, cats in plan.items():
            for cat, base in cats.items():
                budget = base * (1 + 0.1 * np.sin(m.month / 12 * 2 * np.pi)) if cat in ("Events", "Campaigns") else base
                drift = {"Cloud": 1.12, "Travel": 1.08, "Contractors": 0.85}.get(cat, 1.0)
                actual = budget * drift * rng.uniform(0.9, 1.1) if m <= today else np.nan
                rows.append((m, dept, cat, round(budget, 2), None if np.isnan(actual) else round(actual, 2)))
    return pd.DataFrame(rows, columns=["PERIOD", "DEPARTMENT", "CATEGORY", "BUDGET", "ACTUAL"])


@st.cache_data(ttl=600, show_spinner=False)
def load_budget() -> pd.DataFrame:
    if DEMO:
        df = demo_budget()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(BUDGET_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    df["PERIOD"] = pd.to_datetime(df["PERIOD"], errors="coerce").dt.to_period("M").dt.to_timestamp()
    for c in ("BUDGET", "ACTUAL"):
        df[c] = pd.to_numeric(df[c], errors="coerce")
    for c in ("DEPARTMENT", "CATEGORY"):
        df[c] = df[c].fillna("Unknown").astype(str)
    return df.dropna(subset=["PERIOD"])


st.title("Budget vs actual")
if DEMO:
    st.caption("Showing generated demo data — connect your own table in the DATA section.")

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

with st.sidebar:
    st.header("Filters")
    years = sorted(data["PERIOD"].dt.year.unique(), reverse=True)
    year = st.selectbox("Year", years)
    departments = st.multiselect("Department", sorted(data["DEPARTMENT"].unique()))

year_rows = data[data["PERIOD"].dt.year == year]
if departments:
    year_rows = year_rows[year_rows["DEPARTMENT"].isin(departments)]
closed = year_rows[year_rows["ACTUAL"].notna()]
if closed.empty:
    st.info("No actuals booked for this year yet.")
    st.stop()
last_closed = closed["PERIOD"].max()
ytd = year_rows[year_rows["PERIOD"] <= last_closed]

budget_ytd, actual_ytd = ytd["BUDGET"].sum(), ytd["ACTUAL"].sum()
budget_year = year_rows["BUDGET"].sum()
months_done = ytd["PERIOD"].nunique()
forecast = actual_ytd / months_done * year_rows["PERIOD"].nunique() if months_done else 0

k = st.columns(4)
k[0].metric("Actual YTD", f"{actual_ytd:,.0f}")
k[1].metric("Budget YTD", f"{budget_ytd:,.0f}")
k[2].metric("Variance YTD", f"{actual_ytd - budget_ytd:+,.0f}",
            f"{(actual_ytd - budget_ytd) / budget_ytd:+.1%}" if budget_ytd else None, delta_color="inverse")
k[3].metric("Full-year run rate", f"{forecast:,.0f}",
            f"{(forecast - budget_year) / budget_year:+.1%} vs budget" if budget_year else None, delta_color="inverse")
st.caption(f"Year to date through {last_closed:%B %Y}; run rate = average month so far × months in the year.")

monthly = year_rows.groupby("PERIOD", as_index=False)[["BUDGET", "ACTUAL"]].sum(min_count=1)
monthly["CUM_BUDGET"] = monthly["BUDGET"].cumsum()
monthly["CUM_ACTUAL"] = monthly["ACTUAL"].cumsum()
left, right = st.columns(2)
fig = go.Figure()
fig.add_bar(x=monthly["PERIOD"], y=monthly["BUDGET"], name="Budget", marker_color="#c7d2e0")
fig.add_bar(x=monthly["PERIOD"], y=monthly["ACTUAL"], name="Actual", marker_color=COLORS[0])
fig.update_layout(title="By month", barmode="group", legend_title_text="", margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

fig = go.Figure()
fig.add_scatter(x=monthly["PERIOD"], y=monthly["CUM_BUDGET"], name="Budget", line=dict(dash="dash", color="#7f8c9d"))
fig.add_scatter(x=monthly["PERIOD"], y=monthly["CUM_ACTUAL"], name="Actual", line=dict(color=COLORS[0], width=3))
fig.update_layout(title="Cumulative", legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")

lines = ytd.groupby(["DEPARTMENT", "CATEGORY"], as_index=False)[["BUDGET", "ACTUAL"]].sum()
lines["VARIANCE"] = lines["ACTUAL"] - lines["BUDGET"]
lines["VARIANCE_PCT"] = np.where(lines["BUDGET"] != 0, lines["VARIANCE"] / lines["BUDGET"], np.nan)

by_dept = lines.groupby("DEPARTMENT", as_index=False)[["BUDGET", "ACTUAL", "VARIANCE"]].sum()
by_dept["STATUS"] = np.where(by_dept["VARIANCE"] > by_dept["BUDGET"] * TOLERANCE, "Over budget",
                             np.where(by_dept["VARIANCE"] < 0, "Under budget", "On track"))
fig = px.bar(by_dept.sort_values("VARIANCE"), x="VARIANCE", y="DEPARTMENT", orientation="h", color="STATUS",
             color_discrete_map={"Over budget": "#d62728", "On track": "#7f8c9d", "Under budget": "#2ca02c"},
             labels={"VARIANCE": "Variance YTD (actual − budget)", "DEPARTMENT": ""}, title="Variance by department")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
st.plotly_chart(fig, width="stretch")

st.subheader("Lines over budget")
over = lines[lines["VARIANCE_PCT"] > TOLERANCE].sort_values("VARIANCE", ascending=False).reset_index(drop=True)
if over.empty:
    st.success(f"No line is more than {TOLERANCE:.0%} over its year-to-date budget.")
else:
    st.dataframe(over, width="stretch", column_config={
        "BUDGET": st.column_config.NumberColumn("Budget YTD", format="localized"),
        "ACTUAL": st.column_config.NumberColumn("Actual YTD", format="localized"),
        "VARIANCE": st.column_config.NumberColumn("Variance", format="localized"),
        "VARIANCE_PCT": st.column_config.NumberColumn("Variance %", format="percent"),
    })

with st.expander("All lines"):
    st.dataframe(lines.sort_values(["DEPARTMENT", "CATEGORY"]).reset_index(drop=True), width="stretch")
    st.download_button("Download CSV", lines.to_csv(index=False), "budget_vs_actual.csv", "text/csv")
