"""Qahwa House season risk simulator: the Week 14 Streamlit app of DTE631 Business Decision Analytics.

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

Two Monte Carlo models, one per tab:
* Gift boxes: how many Ramadan gift boxes a branch should order, once, before the season. Demand = the branch's
  forecast x a forecast-error ratio drawn from normal(mean, sd) of the past seasons (data/qahwa_giftbox_demand.csv:
  the copy in the repository when it is there, otherwise the one on the course website).
* Catering bid: what to bid for a contract against rivals whose bids are unknown, with a limit on the chance of a loss.
"""
from pathlib import Path

import numpy as np
import pandas as pd
import streamlit as st
from scipy import stats

URL = "https://chebil.github.io/BusinessDecision/data/qahwa_giftbox_demand.csv"
LOCAL = Path(__file__).resolve().parents[2] / "data" / "qahwa_giftbox_demand.csv"


@st.cache_data
def load() -> pd.DataFrame:
    return pd.read_csv(LOCAL if LOCAL.exists() else URL)


def season_profit(order, demand, price, cost, leftover_value):
    sold = np.minimum(order, demand)
    return price * sold + leftover_value * (order - sold) - cost * order


def risk(profit: np.ndarray) -> dict:
    return {"mean": profit.mean(), "se": profit.std(ddof=1) / np.sqrt(len(profit)), "p_loss": (profit < 0).mean(),
            "p5": np.percentile(profit, 5), "p95": np.percentile(profit, 95)}


st.set_page_config(page_title="Qahwa House season risk simulator", layout="wide")
boxes = load()
past = boxes[boxes["season"] < 2026]
ratio = past["demand"] / past["forecast"]
r_mean, r_sd = ratio.mean(), ratio.std()
forecasts = boxes[boxes["season"] == 2026].set_index("branch")["forecast"]

st.title("Qahwa House · season risk simulator")
st.caption("Monte Carlo simulation: every uncertain input is drawn thousands of times, and each plan is judged on the "
           "whole distribution of its profit, not only on its mean.")
gift, bid_tab = st.tabs(["Ramadan gift boxes", "Catering bid"])

# ================================================================================================================
with st.sidebar:
    st.header("Gift boxes")
    branch = st.selectbox("Branch", list(forecasts.index))
    price = st.number_input("Selling price (SAR)", 50, 400, 150, 5)
    cost = st.number_input("Supplier's price (SAR)", 10, 300, 95, 5)
    leftover_value = st.number_input("Value of a box left after Eid (SAR)", 0, 300, 20, 5)
    runs = st.select_slider("Simulated seasons", [1_000, 5_000, 10_000, 50_000], value=10_000)
    seed = st.number_input("Random seed", 0, 10_000, 14)

forecast = int(forecasts[branch])
mu, sigma = forecast * r_mean, forecast * r_sd
valid = cost < price and leftover_value < cost
def gift_boxes():
    if not valid:
        st.error("The model needs leftover value < supplier's price < selling price.")
        return
    cu, co = price - cost, cost - leftover_value
    critical_ratio = cu / (cu + co)
    recommended = int(round(stats.norm.ppf(critical_ratio, mu, sigma)))
    st.markdown(f"**{branch}**: forecast {forecast} boxes. Past forecasts ran at {r_mean:.1%} of demand on average, "
                f"with a spread of {r_sd:.1%}, so demand is modelled as normal({mu:.0f}, {sigma:.0f}). "
                f"Critical ratio {cu} / ({cu} + {co}) = **{critical_ratio:.3f}** → recommended order **{recommended}** boxes.")
    order = st.slider("Boxes to order", 0, 2 * forecast, recommended)

    rng = np.random.default_rng(int(seed))
    demand = np.maximum(np.round(forecast * rng.normal(r_mean, r_sd, runs)), 0)   # the same seasons for every order
    profit = season_profit(order, demand, price, cost, leftover_value)
    r = risk(profit)

    k = st.columns(5)
    k[0].metric("Mean profit (SAR)", f"{r['mean']:,.0f}", help=f"± {1.96 * r['se']:,.0f} (95%, from {runs:,} runs)")
    k[1].metric("P(loss)", f"{r['p_loss']:.1%}")
    k[2].metric("5th percentile (SAR)", f"{r['p5']:,.0f}", help="Only 1 season in 20 ends below this profit.")
    k[3].metric("P(sell out)", f"{(demand > order).mean():.1%}")
    k[4].metric("Boxes left (mean)", f"{np.maximum(order - demand, 0).mean():.0f}")

    left, right = st.columns(2)
    with left:
        st.subheader("Profit of the season")
        counts, edges = np.histogram(profit / 1000, bins=40)
        st.bar_chart(pd.DataFrame({"seasons": counts}, index=edges[:-1].round(1)), x_label="profit (thousand SAR)",
                     y_label="simulated seasons")
    with right:
        st.subheader("Every order, on the same seasons")
        grid = np.unique(np.linspace(0.5 * forecast, 1.5 * forecast, 81).round().astype(int))
        sweep = pd.DataFrame([{**risk(season_profit(q, demand, price, cost, leftover_value)), "order": q} for q in grid])
        st.line_chart(sweep.set_index("order")[["mean", "p5"]].rename(columns={"mean": "mean profit", "p5": "5th percentile"}),
                      x_label="boxes ordered", y_label="SAR")
        best = int(sweep.loc[sweep["mean"].idxmax(), "order"])
        st.caption(f"Highest simulated mean profit: {best} boxes (the critical ratio says {recommended}).")

    st.subheader("All branches: the recommended order against the habit (forecast + 20%)")
    rows = []
    for b, f in forecasts.items():
        d = np.maximum(np.round(f * np.random.default_rng(int(seed)).normal(r_mean, r_sd, runs)), 0)
        q = int(round(stats.norm.ppf(critical_ratio, f * r_mean, f * r_sd)))
        h = int(round(1.2 * f))
        pq, ph = season_profit(q, d, price, cost, leftover_value), season_profit(h, d, price, cost, leftover_value)
        rows.append({"branch": b, "forecast": f, "recommended": q, "mean profit": pq.mean(), "P(loss)": (pq < 0).mean(),
                     "habit (+20%)": h, "habit mean profit": ph.mean(), "habit P(loss)": (ph < 0).mean()})
    table = pd.DataFrame(rows).set_index("branch")
    st.dataframe(table.style.format({"mean profit": "{:,.0f}", "habit mean profit": "{:,.0f}", "P(loss)": "{:.1%}",
                                     "habit P(loss)": "{:.1%}"}), width="stretch")
    st.info("The model assumes demand cannot be served after a sell-out and that unsold boxes are cleared after Eid at "
            "the leftover value. It knows only the forecast errors of past seasons: a new competitor, a supply problem "
            "or a change in the box itself is not in that history.")

with gift:
    gift_boxes()


# ================================================================================================================
def catering_bid():
    st.markdown("A client invites sealed bids; the **lowest bid wins** if it is within the client's budget. "
                "Profit = bid − cost if Qahwa House wins, 0 otherwise. All amounts in thousand SAR.")
    c1, c2, c3 = st.columns(3)
    with c1:
        st.markdown("**Our cost** (triangular)")
        cmin = st.number_input("minimum", 0.0, 1000.0, 180.0, 5.0, key="cmin")
        cmode = st.number_input("most likely", 0.0, 1000.0, 200.0, 5.0, key="cmode")
        cmax = st.number_input("maximum", 0.0, 1000.0, 260.0, 5.0, key="cmax")
    with c2:
        st.markdown("**Rivals**")
        n_rivals = st.number_input("possible rivals", 0, 10, 4, key="nr")
        p_enter = st.slider("chance each one bids", 0.0, 1.0, 0.5, 0.05, key="pe")
        budget = st.number_input("client's budget", 0.0, 2000.0, 300.0, 5.0, key="budget")
    with c3:
        st.markdown("**A rival's bid** (triangular)")
        bmin = st.number_input("minimum", 0.0, 1000.0, 210.0, 5.0, key="bmin")
        bmode = st.number_input("most likely", 0.0, 1000.0, 245.0, 5.0, key="bmode")
        bmax = st.number_input("maximum", 0.0, 1000.0, 290.0, 5.0, key="bmax")
    limit = st.slider("Highest acceptable chance of a loss", 0.0, 0.30, 0.05, 0.01, format="%.2f")

    if not (cmin <= cmode <= cmax and cmin < cmax and bmin <= bmode <= bmax and bmin < bmax):
        st.error("Each triangular distribution needs minimum ≤ most likely ≤ maximum, with minimum < maximum.")
        return
    rng = np.random.default_rng(int(seed) + 1)
    T = runs
    cost_k = rng.triangular(cmin, cmode, cmax, T)
    enters = rng.random((T, int(n_rivals))) < p_enter
    lowest = np.where(enters, rng.triangular(bmin, bmode, bmax, (T, int(n_rivals))), np.inf).min(axis=1, initial=np.inf)

    rows = []
    top = min(budget, 2 * max(bmax, cmax))          # bids above the budget never win
    for b in np.arange(np.floor(cmin / 5) * 5, top + 0.1, 5.0):
        win = (b < lowest) & (b <= budget)
        pr = np.where(win, b - cost_k, 0.0)
        rows.append({"bid": b, "P(win)": win.mean(), "mean profit": pr.mean(), "P(loss)": (pr < 0).mean(),
                     "5th percentile": np.percentile(pr, 5)})
    bids = pd.DataFrame(rows).set_index("bid")
    best_bid = bids["mean profit"].idxmax()
    ok = bids[bids["P(loss)"] <= limit]
    m = st.columns(3)
    m[0].metric("Highest mean profit", f"bid {best_bid:,.0f}", f"mean {bids.loc[best_bid, 'mean profit']:.1f}, "
                f"P(loss) {bids.loc[best_bid, 'P(loss)']:.1%}", delta_color="off")
    if len(ok) and ok["mean profit"].max() > 0:
        safe = ok["mean profit"].idxmax()
        m[1].metric(f"Best bid with P(loss) ≤ {limit:.0%}", f"bid {safe:,.0f}",
                    f"mean {bids.loc[safe, 'mean profit']:.1f}, P(loss) {bids.loc[safe, 'P(loss)']:.1%}", delta_color="off")
        m[2].metric("Price of the safety", f"{1000 * (bids.loc[best_bid, 'mean profit'] - bids.loc[safe, 'mean profit']):,.0f} SAR",
                    help="Mean profit given up to respect the limit.")
    else:
        m[1].metric(f"Best bid with P(loss) ≤ {limit:.0%}", "none")
    st.line_chart(bids[["mean profit"]], x_label="bid (thousand SAR)", y_label="mean profit (thousand SAR)")
    st.dataframe(bids.style.format({"P(win)": "{:.1%}", "mean profit": "{:.2f}", "P(loss)": "{:.1%}",
                                    "5th percentile": "{:.1f}"}), width="stretch")


with bid_tab:
    catering_bid()
