"""Qahwa House bean order planner: the Week 8 Streamlit app of DTE631 Business Decision Analytics.

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

It reads the weekly coffee-bean use of each branch (data/qahwa_weekly_demand.csv): the copy in the repository when it
is there, otherwise the one on the course website. For the chosen branch and method it tests the forecast on the last
weeks of the data (the holdout), forecasts the coming weeks, and turns the forecast into an order with a safety buffer.
"""
from pathlib import Path
from statistics import NormalDist

import numpy as np
import pandas as pd
import streamlit as st
from statsmodels.tsa.holtwinters import ExponentialSmoothing

URL = "https://chebil.github.io/BusinessDecision/data/qahwa_weekly_demand.csv"
LOCAL = Path(__file__).resolve().parents[2] / "data" / "qahwa_weekly_demand.csv"
BRANCHES = ["Olaya", "Corniche", "Al Faisaliyah", "University"]
METHODS = ["Holt-Winters", "Same week last year", "Moving average (4 weeks)", "Average", "Last week (naive)"]
SEASON = 52


@st.cache_data
def load() -> pd.DataFrame:
    df = pd.read_csv(LOCAL if LOCAL.exists() else URL, parse_dates=["week_start"])
    return df.pivot(index="week_start", columns="branch", values="beans_kg")[BRANCHES].asfreq("W-MON")


@st.cache_data(show_spinner=False)
def forecast(values: tuple, start: str, h: int, method: str) -> np.ndarray:
    """h forecasts after the series `values` (weekly, starting on `start`), with one of METHODS."""
    s = pd.Series(values, index=pd.date_range(start, periods=len(values), freq="W-MON"))
    if method == "Last week (naive)":
        return np.repeat(s.iloc[-1], h)
    if method == "Average":
        return np.repeat(s.mean(), h)
    if method == "Moving average (4 weeks)":
        return np.repeat(s.iloc[-4:].mean(), h)
    if method == "Same week last year":
        return np.array([s.iloc[-SEASON + (i % SEASON)] for i in range(h)])
    model = ExponentialSmoothing(s, trend="add", seasonal="add", seasonal_periods=SEASON).fit()
    return model.forecast(h).to_numpy()


def run(s: pd.Series, h: int, method: str) -> np.ndarray:
    return forecast(tuple(s.to_numpy()), str(s.index[0].date()), h, method)


def scores(actual: np.ndarray, pred: np.ndarray) -> dict:
    e = actual - pred
    return {"MAE": np.abs(e).mean(), "RMSE": np.sqrt((e ** 2).mean()), "MAPE (%)": (np.abs(e) / actual).mean() * 100}


st.set_page_config(page_title="Qahwa House bean planner", layout="wide")
kg = load()

# ---- sidebar: the decision's settings ---------------------------------------------------------
st.sidebar.header("Settings")
branch = st.sidebar.selectbox("Branch", BRANCHES)
method = st.sidebar.radio("Forecasting method", METHODS)
horizon = st.sidebar.slider("Weeks to order for", 4, 12, 8)
service = st.sidebar.slider("Service level (chance the order covers the weeks)", 0.50, 0.99, 0.90, 0.01, format="%.2f")
adjust = st.sidebar.number_input("Manual adjustment (%)", -50, 50, 0, 5,
                                 help="For what the model cannot know: a promotion, a holiday that moved, a supply problem.")
z = NormalDist().inv_cdf(service)

s = kg[branch]
train, test = s.iloc[:-horizon], s.iloc[-horizon:]
next_weeks = pd.date_range(s.index[-1] + pd.Timedelta(weeks=1), periods=horizon, freq="W-MON")

st.title("Qahwa House · bean order planner")
st.caption(f"Weekly coffee beans used, {s.index[0]:%d %b %Y} to {s.index[-1]:%d %b %Y}. "
           f"Each method is tested on the last {horizon} weeks, which it does not see, before it forecasts the next {horizon}.")

# ---- the holdout test of the chosen method -----------------------------------------------------
held = run(train, horizon, method)
sc = scores(test.to_numpy(), held)
future = run(s, horizon, method) * (1 + adjust / 100)
buffer = z * sc["RMSE"] * np.sqrt(horizon)
order = float(np.ceil(future.sum() + buffer))

k1, k2, k3, k4 = st.columns(4)
k1.metric("Holdout MAE (kg)", f"{sc['MAE']:.2f}")
k2.metric("Holdout RMSE (kg)", f"{sc['RMSE']:.2f}")
k3.metric("Holdout MAPE", f"{sc['MAPE (%)']:.1f}%")
k4.metric(f"Order for the next {horizon} weeks (kg)", f"{order:,.0f}",
          help=f"forecast total {future.sum():.1f} kg + buffer {buffer:.1f} kg (z = {z:.2f} × RMSE × √{horizon})")

# ---- chart: history, holdout forecast, future forecast -------------------------------------------
st.subheader(f"{branch}: the last year, the test and the forecast")
chart = pd.DataFrame(index=s.index[-52:].append(next_weeks))
chart["actual"] = s
chart["test forecast"] = pd.Series(held, index=test.index)
chart["forecast"] = pd.Series(future, index=next_weeks)
st.line_chart(chart, y_label="kg per week")

left, right = st.columns(2)
with left:
    st.subheader("Every method on the holdout")
    table = pd.DataFrame({m: scores(test.to_numpy(), run(train, horizon, m)) for m in METHODS}).T
    st.dataframe(table.style.format("{:.2f}").highlight_min(axis=0, color="#8fd6b055"), width="stretch")
    st.caption("RMSE punishes big misses most; MAPE inflates errors in small weeks. "
               "Beans are bought by the kilogram, so compare in kg.")
with right:
    st.subheader(f"Orders for every branch ({method})")
    rows = []
    for b in BRANCHES:
        sb = kg[b]
        rmse_b = scores(sb.iloc[-horizon:].to_numpy(), run(sb.iloc[:-horizon], horizon, method))["RMSE"]
        fc = run(sb, horizon, method) * (1 + adjust / 100)
        rows.append({"branch": b, "forecast (kg)": fc.sum(), "buffer (kg)": z * rmse_b * np.sqrt(horizon),
                     "last week × weeks": sb.iloc[-1] * horizon})
    orders = pd.DataFrame(rows).set_index("branch")
    orders["order (kg)"] = np.ceil(orders["forecast (kg)"] + orders["buffer (kg)"])
    st.dataframe(orders.style.format("{:,.1f}"), width="stretch")
    st.metric("Total order (kg)", f"{orders['order (kg)'].sum():,.0f}")

with st.expander("Weekly forecast for this branch"):
    st.dataframe(pd.DataFrame({"week starting": next_weeks.date, "forecast (kg)": future.round(1)}), hide_index=True)

st.info("A forecast only knows the calendar of past years. Ramadan and the two Eids come about 11 days earlier each "
        "year, and one-off events are not in the history: check the coming weeks and use the manual adjustment.")
