"""Finance KPIs — revenue, gross margin, operating expenses and operating
profit by month, with a P&L bridge and the monthly P&L table."""

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="Finance KPIs", 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).
# ACCOUNT_GROUP must be one of: Revenue, Cost of sales, Operating expenses.
# AMOUNT is positive for revenue and for costs.
DEMO = True
LEDGER_SQL = """
SELECT PERIOD, ACCOUNT_GROUP, ACCOUNT, DEPARTMENT, AMOUNT
FROM {{DATABASE}}.{{SCHEMA}}.GL_MONTHLY
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = px.colors.qualitative.Safe
GROUPS = ["Revenue", "Cost of sales", "Operating expenses"]


def demo_ledger() -> pd.DataFrame:
    rng = np.random.default_rng(11)
    months = pd.date_range(end=pd.Timestamp.today().normalize().replace(day=1), periods=24, freq="MS")
    rows = []
    for i, m in enumerate(months):
        growth = 1 + 0.015 * i
        season = 1 + 0.12 * np.sin((m.month - 2) / 12 * 2 * np.pi)
        for account, base in (("Product sales", 820_000), ("Subscriptions", 310_000), ("Services", 140_000)):
            rows.append((m, "Revenue", account, "Sales", base * growth * season * rng.uniform(0.95, 1.05)))
        for account, share in (("Materials", 0.28), ("Hosting", 0.06), ("Delivery staff", 0.07)):
            rows.append((m, "Cost of sales", account, "Operations", 1_270_000 * growth * season * share * rng.uniform(0.95, 1.07)))
        for dept, base in (("Sales", 150_000), ("Marketing", 95_000), ("R&D", 180_000), ("G&A", 85_000)):
            for account, share in (("Salaries", 0.7), ("Software", 0.12), ("Travel", 0.08), ("Other", 0.1)):
                rows.append((m, "Operating expenses", account, dept, base * (1 + 0.008 * i) * share * rng.uniform(0.9, 1.1)))
    df = pd.DataFrame(rows, columns=["PERIOD", "ACCOUNT_GROUP", "ACCOUNT", "DEPARTMENT", "AMOUNT"])
    df["AMOUNT"] = df["AMOUNT"].round(2)
    return df


@st.cache_data(ttl=600, show_spinner=False)
def load_ledger() -> pd.DataFrame:
    if DEMO:
        df = demo_ledger()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(LEDGER_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()
    df["AMOUNT"] = pd.to_numeric(df["AMOUNT"], errors="coerce").fillna(0)
    for c in ("ACCOUNT_GROUP", "ACCOUNT", "DEPARTMENT"):
        df[c] = df[c].fillna("Unknown").astype(str)
    return df.dropna(subset=["PERIOD"])


def pnl(df: pd.DataFrame) -> pd.DataFrame:
    """One row per month: revenue, cost of sales, gross profit, opex, operating profit, margins."""
    p = df.pivot_table(index="PERIOD", columns="ACCOUNT_GROUP", values="AMOUNT", aggfunc="sum", fill_value=0)
    for g in GROUPS:
        if g not in p:
            p[g] = 0.0
    out = pd.DataFrame(index=p.index)
    out["REVENUE"] = p["Revenue"]
    out["COST_OF_SALES"] = p["Cost of sales"]
    out["GROSS_PROFIT"] = out["REVENUE"] - out["COST_OF_SALES"]
    out["OPEX"] = p["Operating expenses"]
    out["OPERATING_PROFIT"] = out["GROSS_PROFIT"] - out["OPEX"]
    rev = out["REVENUE"].replace(0, np.nan)
    out["GROSS_MARGIN"] = out["GROSS_PROFIT"] / rev
    out["OPERATING_MARGIN"] = out["OPERATING_PROFIT"] / rev
    return out.reset_index()


st.title("Finance KPIs")
if DEMO:
    st.caption("Showing generated demo data — connect your own ledger in the DATA section.")

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

months = sorted(ledger["PERIOD"].unique())
with st.sidebar:
    st.header("Filters")
    last = st.select_slider("Month", options=months, value=months[-1], format_func=lambda m: pd.Timestamp(m).strftime("%b %Y"))
    view = st.radio("KPIs for", ["Month", "Year to date", "Last 12 months"], index=1)

monthly = pnl(ledger)
last = pd.Timestamp(last)
if view == "Month":
    window = monthly[monthly["PERIOD"] == last]
    prior = monthly[monthly["PERIOD"] == last - pd.DateOffset(years=1)]
elif view == "Year to date":
    window = monthly[(monthly["PERIOD"].dt.year == last.year) & (monthly["PERIOD"] <= last)]
    py = last - pd.DateOffset(years=1)
    prior = monthly[(monthly["PERIOD"].dt.year == py.year) & (monthly["PERIOD"] <= py)]
else:
    window = monthly[(monthly["PERIOD"] > last - pd.DateOffset(months=12)) & (monthly["PERIOD"] <= last)]
    prior = monthly[(monthly["PERIOD"] > last - pd.DateOffset(months=24)) & (monthly["PERIOD"] <= last - pd.DateOffset(months=12))]


def totals(frame: pd.DataFrame) -> dict:
    s = frame[["REVENUE", "COST_OF_SALES", "GROSS_PROFIT", "OPEX", "OPERATING_PROFIT"]].sum()
    s["GROSS_MARGIN"] = s["GROSS_PROFIT"] / s["REVENUE"] if s["REVENUE"] else 0
    s["OPERATING_MARGIN"] = s["OPERATING_PROFIT"] / s["REVENUE"] if s["REVENUE"] else 0
    return s.to_dict()


now, before = totals(window), totals(prior)


def change(key, pct=False):
    if not before.get("REVENUE"):
        return None
    if pct:
        return f"{(now[key] - before[key]) * 100:+.1f} pts"
    return f"{(now[key] - before[key]) / abs(before[key]):+.1%}" if before[key] else None


k = st.columns(5)
k[0].metric("Revenue", f"{now['REVENUE']:,.0f}", change("REVENUE"))
k[1].metric("Gross margin", f"{now['GROSS_MARGIN']:.1%}", change("GROSS_MARGIN", pct=True))
k[2].metric("Operating expenses", f"{now['OPEX']:,.0f}", change("OPEX"), delta_color="inverse")
k[3].metric("Operating profit", f"{now['OPERATING_PROFIT']:,.0f}", change("OPERATING_PROFIT"))
k[4].metric("Operating margin", f"{now['OPERATING_MARGIN']:.1%}", change("OPERATING_MARGIN", pct=True))
st.caption(f"{view} to {last:%b %Y}, change vs the same period a year earlier.")

trend = monthly[monthly["PERIOD"] <= last].tail(24)
left, right = st.columns(2)
fig = go.Figure()
fig.add_bar(x=trend["PERIOD"], y=trend["REVENUE"], name="Revenue", marker_color=COLORS[0])
fig.add_bar(x=trend["PERIOD"], y=trend["OPERATING_PROFIT"], name="Operating profit", marker_color=COLORS[1])
fig.update_layout(title="Revenue and operating profit", barmode="group", legend_title_text="", margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

margins = trend.melt(id_vars="PERIOD", value_vars=["GROSS_MARGIN", "OPERATING_MARGIN"], var_name="MARGIN", value_name="VALUE")
margins["MARGIN"] = margins["MARGIN"].map({"GROSS_MARGIN": "Gross margin", "OPERATING_MARGIN": "Operating margin"})
fig = px.line(margins, x="PERIOD", y="VALUE", color="MARGIN", markers=True, color_discrete_sequence=COLORS,
              labels={"VALUE": "", "PERIOD": ""}, title="Margins")
fig.update_layout(yaxis_tickformat=".0%", legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")

left, right = st.columns(2)
fig = go.Figure(go.Waterfall(
    x=["Revenue", "Cost of sales", "Gross profit", "Operating expenses", "Operating profit"],
    measure=["absolute", "relative", "total", "relative", "total"],
    y=[now["REVENUE"], -now["COST_OF_SALES"], 0, -now["OPEX"], 0],
    connector={"line": {"color": "#999"}},
))
fig.update_layout(title=f"P&L bridge — {view.lower()}", margin=dict(t=50, b=10), showlegend=False)
left.plotly_chart(fig, width="stretch")

scope = ledger[(ledger["ACCOUNT_GROUP"] == "Operating expenses") & ledger["PERIOD"].isin(window["PERIOD"])]
opex = scope.groupby(["DEPARTMENT", "ACCOUNT"], as_index=False)["AMOUNT"].sum()
fig = px.bar(opex, x="DEPARTMENT", y="AMOUNT", color="ACCOUNT", color_discrete_sequence=COLORS,
             labels={"AMOUNT": "Operating expenses", "DEPARTMENT": ""}, title="Operating expenses by department")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")

st.subheader("Monthly P&L")
table = trend.tail(12).set_index("PERIOD")[["REVENUE", "COST_OF_SALES", "GROSS_PROFIT", "OPEX", "OPERATING_PROFIT", "OPERATING_MARGIN"]]
table.index = table.index.strftime("%b %Y")
table = table.T
table.index = ["Revenue", "Cost of sales", "Gross profit", "Operating expenses", "Operating profit", "Operating margin"]
st.dataframe(table.apply(lambda col: col.map(lambda v: f"{v:.1%}" if abs(v) < 1.5 else f"{v:,.0f}")), width="stretch")
