"""Streamlit dashboard backed by the Lunch Money store.

Run: streamlit run dashboard.py
Visit: http://localhost:8501
"""
from datetime import date, timedelta

import pandas as pd
import streamlit as st

import db

st.set_page_config(page_title="Finances", layout="wide")
st.title("💰 Finances")

db.init_db()
txns = db.list_recent_transactions(days=180)
if not txns:
    st.warning("No transactions yet. Run `python pull_transactions.py` first.")
    st.stop()

df = pd.DataFrame(txns)
df["date"] = pd.to_datetime(df["date"])
df["category"] = df["category_name"].fillna("Uncategorized")
df["month"] = df["date"].dt.to_period("M").astype(str)

# Lunch Money: positive = expense, negative = income
df["is_outflow"] = df["amount"] > 0
df["abs_amount"] = df["amount"].abs()

# ---- KPIs ----
col1, col2, col3, col4 = st.columns(4)
last_30 = df[df["date"] >= pd.Timestamp(date.today() - timedelta(days=30))]
col1.metric("Spending (30d)", f"${last_30[last_30['is_outflow']]['amount'].sum():,.0f}")
col2.metric("Income (30d)", f"${(-last_30[~last_30['is_outflow']]['amount']).sum():,.0f}")
col3.metric("Transactions (30d)", len(last_30))
col4.metric("Unique payees (30d)", last_30["payee"].nunique())

st.divider()

st.subheader("Spending by category (last 30 days)")
cat = (
    last_30[last_30["is_outflow"]]
    .groupby("category")["amount"]
    .sum()
    .sort_values(ascending=False)
    .head(15)
)
st.bar_chart(cat)

st.subheader("Monthly spending trend")
monthly = df[df["is_outflow"]].groupby("month")["amount"].sum()
st.line_chart(monthly)

st.subheader("Lunch Money's detected recurring expenses")
recurring = pd.DataFrame(db.list_recurring())
if not recurring.empty:
    st.dataframe(
        recurring[["payee", "cadence", "typical_amount", "start_date", "end_date"]],
        use_container_width=True,
    )
else:
    st.caption("No recurring expenses detected yet (Lunch Money needs ~2 cycles of data).")

st.subheader("Recent transactions")
recent_view = df.sort_values("date", ascending=False).head(50)[
    ["date", "payee", "amount", "category", "is_pending", "status"]
]
st.dataframe(recent_view, use_container_width=True)
