"""Qahwa House orders explorer: the Week 4 Streamlit app of DTE631 Business Decision Analytics.

Run it:   streamlit run week04/app/app.py          (from the repository root)
Deploy:   Streamlit Community Cloud, main file path week04/app/app.py

It reads a sample of 2025 receipts (data/qahwa_orders_2025.csv): the copy in the repository when it is there,
otherwise the one on the course website.
"""
from pathlib import Path

import pandas as pd
import streamlit as st

URL = "https://chebil.github.io/BusinessDecision/data/qahwa_orders_2025.csv"
LOCAL = Path(__file__).resolve().parents[2] / "data" / "qahwa_orders_2025.csv"
CATEGORIES = {"Drinks": "drink_sar", "Food": "food_sar"}


@st.cache_data
def load() -> pd.DataFrame:
    df = pd.read_csv(LOCAL if LOCAL.exists() else URL)
    df["date"] = pd.to_datetime(df["date"])
    df["has_food"] = df["food_items"] > 0
    return df


st.set_page_config(page_title="Qahwa House explorer", layout="wide")
orders = load()

# ---- sidebar: filters ------------------------------------------------------------------------
st.sidebar.header("Filters")
branches = st.sidebar.multiselect("Branches", sorted(orders["branch"].unique()), default=sorted(orders["branch"].unique()))
categories = st.sidebar.multiselect("Categories", list(CATEGORIES), default=list(CATEGORIES))
who = st.sidebar.radio("Customers", ["All", "App users", "Others"])
lo, hi = orders["date"].min().date(), orders["date"].max().date()
period = st.sidebar.date_input("Dates", value=(lo, hi), min_value=lo, max_value=hi)

view = orders[orders["branch"].isin(branches)]
if who != "All":
    view = view[view["app_user"] == (1 if who == "App users" else 0)]
if isinstance(period, (list, tuple)) and len(period) == 2:
    view = view[(view["date"].dt.date >= period[0]) & (view["date"].dt.date <= period[1])]
cols = [CATEGORIES[c] for c in categories]

st.title("Qahwa House · orders explorer")
if view.empty or not cols:
    st.info("No orders match these filters. Choose at least one branch and one category.")
    st.stop()
view = view.assign(revenue=view[cols].sum(axis=1))

# ---- headline numbers ------------------------------------------------------------------------
k1, k2, k3, k4 = st.columns(4)
k1.metric("Orders", f"{len(view):,}")
k2.metric("Revenue (SAR)", f"{view['revenue'].sum():,.0f}")
k3.metric("Revenue per order (SAR)", f"{view['revenue'].mean():.2f}")
k4.metric("Orders with food", f"{view['has_food'].mean():.0%}")

# ---- pivot table: branch x category ----------------------------------------------------------
st.subheader("Revenue per order by branch and category (SAR)")
pivot = view.groupby("branch")[cols].mean().rename(columns={v: k for k, v in CATEGORIES.items()})
pivot["Total"] = pivot.sum(axis=1)
st.dataframe(pivot.style.format("{:.2f}").highlight_min(axis=0, color="#f4a48c55"), width="stretch")
worst = pivot.drop(columns="Total").stack().idxmin()
st.caption(f"Lowest cell: {worst[1]} at {worst[0]}, {pivot.loc[worst[0], worst[1]]:.2f} SAR per order.")

# ---- chart: weekly revenue per order ---------------------------------------------------------
st.subheader("Weekly revenue per order")
weekly = view.groupby([pd.Grouper(key="date", freq="W"), "branch"])["revenue"].mean().unstack()
st.line_chart(weekly)

# ---- relationships ---------------------------------------------------------------------------
left, right = st.columns(2)
with left:
    st.subheader("App users and basket size")
    overall = view.groupby("app_user")["revenue"].mean().rename({0: "Others", 1: "App users"})
    within = view.pivot_table(index="branch", columns="app_user", values="revenue", aggfunc="mean").rename(columns={0: "Others", 1: "App users"})
    st.write("Overall (SAR per order)")
    st.dataframe(overall.to_frame("SAR per order").style.format("{:.2f}"))
    st.write("Within each branch (SAR per order)")
    st.dataframe(within.style.format("{:.2f}"))
    if len(overall) == 2 and within.dropna().shape[0] > 1:
        up_within = (within["App users"] > within["Others"]).all()
        if up_within and overall["App users"] < overall["Others"]:
            st.warning("Simpson's paradox: app users spend more in every branch, but less overall, "
                       "because most of them order at the branch with the smallest baskets.")
with right:
    st.subheader("Correlation view")
    numeric = ["drinks", "food_items", "drink_sar", "food_sar", "basket_sar", "hour"]
    x = st.selectbox("x", numeric, index=1)
    y = st.selectbox("y", numeric, index=4)
    r = view[x].corr(view[y])
    st.scatter_chart(view, x=x, y=y, height=300)
    st.metric("Correlation r", "n/a" if pd.isna(r) else f"{r:.2f}")
    st.caption("Correlation measures a linear relationship only, and it is not causation: "
               "a third variable, such as the branch, can drive both.")
