"""Inventory — stock value, days of cover and what to reorder, by warehouse
and category."""

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

st.set_page_config(page_title="Inventory", 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 SKU and warehouse (the current snapshot).
DEMO = True
STOCK_SQL = """
SELECT SKU, PRODUCT, CATEGORY, WAREHOUSE, ON_HAND, REORDER_POINT, UNIT_COST, DAILY_DEMAND
FROM {{DATABASE}}.{{SCHEMA}}.INVENTORY
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = px.colors.qualitative.Safe
LEAD_TIME_DAYS = 14


def demo_stock() -> pd.DataFrame:
    rng = np.random.default_rng(21)
    cats = {"Electronics": (80, 400), "Home": (15, 120), "Outdoor": (25, 250), "Office": (5, 60), "Toys": (8, 70)}
    rows = []
    for i in range(1, 161):
        cat = list(cats)[i % len(cats)]
        lo, hi = cats[cat]
        cost = round(rng.uniform(lo, hi), 2)
        demand = round(rng.gamma(2.0, 3.0), 2)
        for wh in ("Berlin", "Rotterdam", "Chicago"):
            if rng.random() < 0.25:
                continue
            reorder = int(demand * LEAD_TIME_DAYS * rng.uniform(0.8, 1.2)) + 5
            on_hand = int(max(0, rng.normal(reorder * 1.6, reorder)))
            rows.append((f"SKU-{i:04d}", f"{cat} item {i}", cat, wh, on_hand, reorder, cost, demand))
    return pd.DataFrame(rows, columns=["SKU", "PRODUCT", "CATEGORY", "WAREHOUSE", "ON_HAND", "REORDER_POINT", "UNIT_COST", "DAILY_DEMAND"])


@st.cache_data(ttl=600, show_spinner=False)
def load_stock() -> pd.DataFrame:
    if DEMO:
        df = demo_stock()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(STOCK_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    for c in ("ON_HAND", "REORDER_POINT", "UNIT_COST", "DAILY_DEMAND"):
        df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0)
    for c in ("SKU", "PRODUCT", "CATEGORY", "WAREHOUSE"):
        df[c] = df[c].fillna("Unknown").astype(str)
    df["STOCK_VALUE"] = df["ON_HAND"] * df["UNIT_COST"]
    df["DAYS_OF_COVER"] = np.where(df["DAILY_DEMAND"] > 0, df["ON_HAND"] / df["DAILY_DEMAND"], np.inf)
    df["STATUS"] = np.select(
        [df["ON_HAND"] <= 0, df["ON_HAND"] <= df["REORDER_POINT"], df["DAYS_OF_COVER"] > 120],
        ["Out of stock", "Reorder", "Overstock"], default="Healthy")
    return df


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

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

with st.sidebar:
    st.header("Filters")
    warehouses = st.multiselect("Warehouse", sorted(stock["WAREHOUSE"].unique()))
    categories = st.multiselect("Category", sorted(stock["CATEGORY"].unique()))

view = stock
if warehouses:
    view = view[view["WAREHOUSE"].isin(warehouses)]
if categories:
    view = view[view["CATEGORY"].isin(categories)]
if view.empty:
    st.info("Nothing matches the filters.")
    st.stop()

finite_cover = view.loc[np.isfinite(view["DAYS_OF_COVER"]), "DAYS_OF_COVER"]
k = st.columns(4)
k[0].metric("Stock value", f"{view['STOCK_VALUE'].sum():,.0f}")
k[1].metric("SKUs to reorder", f"{(view['STATUS'].isin(['Reorder', 'Out of stock'])).sum():,}")
k[2].metric("Out of stock", f"{(view['STATUS'] == 'Out of stock').sum():,}")
k[3].metric("Median days of cover", f"{finite_cover.median():.0f}" if not finite_cover.empty else "–")

left, right = st.columns(2)
by_wh = view.groupby(["WAREHOUSE", "CATEGORY"], as_index=False)["STOCK_VALUE"].sum()
fig = px.bar(by_wh, x="WAREHOUSE", y="STOCK_VALUE", color="CATEGORY", color_discrete_sequence=COLORS,
             labels={"STOCK_VALUE": "Stock value", "WAREHOUSE": ""}, title="Stock value by warehouse")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

status = view.groupby("STATUS", as_index=False).size()
fig = px.pie(status, names="STATUS", values="size", hole=0.55, title="Stock health (SKU × warehouse)",
             color="STATUS", color_discrete_map={"Healthy": "#2ca02c", "Reorder": "#ff7f0e",
                                                 "Out of stock": "#d62728", "Overstock": "#7f8c9d"})
right.plotly_chart(fig, width="stretch")

capped = view.assign(COVER=view["DAYS_OF_COVER"].clip(upper=180))
fig = px.histogram(capped, x="COVER", color="CATEGORY", nbins=36, color_discrete_sequence=COLORS,
                   labels={"COVER": "Days of cover (capped at 180)"}, title="Days of cover")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10), yaxis_title="SKUs")
st.plotly_chart(fig, width="stretch")

st.subheader("Reorder list")
reorder = view[view["STATUS"].isin(["Reorder", "Out of stock"])].copy()
reorder["SUGGESTED_QTY"] = np.ceil(np.maximum(reorder["REORDER_POINT"] * 2 - reorder["ON_HAND"], 0))
reorder["ORDER_VALUE"] = reorder["SUGGESTED_QTY"] * reorder["UNIT_COST"]
reorder = reorder.sort_values(["DAYS_OF_COVER", "ORDER_VALUE"], ascending=[True, False])
cols = ["SKU", "PRODUCT", "WAREHOUSE", "ON_HAND", "REORDER_POINT", "DAYS_OF_COVER", "SUGGESTED_QTY", "ORDER_VALUE", "STATUS"]
if reorder.empty:
    st.success("Nothing to reorder.")
else:
    st.caption(f"Suggested quantity brings stock to twice the reorder point; reorder point ≈ demand over a {LEAD_TIME_DAYS}-day lead time.")
    st.dataframe(reorder[cols].reset_index(drop=True), width="stretch", column_config={
        "DAYS_OF_COVER": st.column_config.NumberColumn("Days of cover", format="%.0f"),
        "ORDER_VALUE": st.column_config.NumberColumn("Order value", format="localized"),
    })
    st.download_button("Download reorder list", reorder[cols].to_csv(index=False), "reorder.csv", "text/csv")
