"""Qahwa House kitchen what-if: the Week 10 Streamlit app of DTE631 Business Decision Analytics.

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

It reads the weekly product-mix model of the central kitchen (data/qahwa_roastery_mix.csv, week 9) and the four offers
on the manager's desk (data/qahwa_roastery_options.csv): the copies in the repository when they are there, otherwise
the ones on the course website. The manager changes the hours, the contributions, the demand limits and the offers;
the app re-solves the linear program with PuLP and shows the plan, the shadow prices, the reduced costs and a sweep of
one resource.
"""
from pathlib import Path

import pandas as pd
import pulp
import streamlit as st

DATA = Path(__file__).resolve().parents[2] / "data"
URL = "https://chebil.github.io/BusinessDecision/data/"
HOURS = {"roast_h": "roaster", "oven_h": "oven", "labour_h": "staff"}


def read(name: str) -> pd.DataFrame:
    return pd.read_csv(DATA / name if (DATA / name).exists() else URL + name)


@st.cache_data
def load():
    mix = read("qahwa_roastery_mix.csv")
    products = mix[mix["product"] != "capacity"].set_index("product")
    capacity = mix.set_index("product").loc["capacity", list(HOURS)].astype(float)
    return products, capacity, read("qahwa_roastery_options.csv")


@st.cache_data(show_spinner=False)
def solve(contrib: tuple, max_batches: tuple, cap: tuple) -> dict:
    """Solve the weekly LP for the given contributions, demand limits and hours (tuples in the order of the table)."""
    names = list(products.index)
    model = pulp.LpProblem("weekly_mix", pulp.LpMaximize)
    x = {p: model.add_variable(f"x{i}", lowBound=0, upBound=max_batches[i]) for i, p in enumerate(names)}
    model += pulp.lpSum(contrib[i] * x[p] for i, p in enumerate(names))
    for j, r in enumerate(HOURS):
        model += pulp.lpSum(float(products.loc[p, r]) * x[p] for p in names) <= cap[j], r
    res = model.solve(pulp.HiGHS(msg=False))
    c = {con.name: con for con in model.constraints()}   # PuLP 4: constraints() is a list; index them by name
    return {"status": res.status.name, "profit": pulp.value(model.objective) or 0.0,
            "plan": [x[p].value() or 0.0 for p in names],
            "slack": [c[r].slack + 0.0 for r in HOURS], "price": [c[r].pi + 0.0 for r in HOURS],
            "dj": [x[p].dj + 0.0 for p in names]}


st.set_page_config(page_title="Qahwa House kitchen what-if", layout="wide")
products, capacity, options = load()
names = list(products.index)

# ---- sidebar: the numbers the manager can change ---------------------------------------------------
st.sidebar.header("Hours per week")
hours = {r: st.sidebar.slider(f"{label.capitalize()} hours", 0, int(capacity[r] * 2), int(capacity[r]))
         for r, label in HOURS.items()}
st.sidebar.header("Offers for next month")
taken = [st.sidebar.checkbox(f"{o['option']} (+{o['amount']} {o['unit']}, {o['weekly_cost_sar']:,} SAR a week)")
         for _, o in options.iterrows()]
with st.sidebar.expander("Contributions and demand"):
    contrib = {p: st.number_input(f"{p}: contribution (SAR a batch)", 0, 5000, int(products.loc[p, "contribution_sar"]), 10)
               for p in names}
    demand = {p: st.number_input(f"{p}: most batches the branches sell", 0, 100, int(products.loc[p, "max_batches"]), 1)
              for p in names}

# the scenario without the offers, and with them
cap0 = tuple(float(hours[r]) for r in HOURS)
dem0 = {p: float(demand[p]) for p in names}
cap1, dem1, cost = list(cap0), dict(dem0), 0
for on, (_, o) in zip(taken, options.iterrows()):
    if on:
        cost += o["weekly_cost_sar"]
        if o["adds_to"].startswith("max_batches:"):
            dem1[o["adds_to"].split(":")[1]] += o["amount"]
        else:
            cap1[list(HOURS).index(o["adds_to"])] += o["amount"]
c_t = tuple(float(contrib[p]) for p in names)
before = solve(c_t, tuple(dem0[p] for p in names), cap0)
after = solve(c_t, tuple(dem1[p] for p in names), tuple(cap1))
this_week = solve(tuple(float(v) for v in products["contribution_sar"]), tuple(float(v) for v in products["max_batches"]),
                  tuple(capacity))

st.title("Qahwa House · kitchen what-if")
st.caption("The weekly product mix of the central kitchen (week 9), re-solved with PuLP every time you change a number. "
           "Shadow prices and reduced costs hold for small changes of one number; for anything larger, the app re-solves.")
if after["status"] != "Optimal":
    st.error(f"The solver reports **{after['status']}**: check the numbers in the sidebar.")
    st.stop()

k1, k2, k3, k4 = st.columns(4)
k1.metric("Weekly contribution (SAR)", f"{after['profit']:,.0f}")
k2.metric("Change from this week's plan (SAR)", f"{after['profit'] - this_week['profit']:+,.0f}")
k3.metric("Cost of the offers (SAR a week)", f"{cost:,.0f}")
k4.metric("Net gain of the offers (SAR a week)", f"{after['profit'] - before['profit'] - cost:+,.0f}",
          help="contribution with the offers − contribution without them − their cost")

left, right = st.columns(2)
with left:
    st.subheader("The plan (batches)")
    plan = pd.DataFrame({"this week": this_week["plan"], "your scenario": after["plan"]}, index=names)
    plan["contribution (SAR)"] = [contrib[p] for p in names]
    plan["reduced cost"] = after["dj"]
    st.dataframe(plan.style.format({"this week": "{:,.1f}", "your scenario": "{:,.1f}", "contribution (SAR)": "{:,.0f}",
                                    "reduced cost": "{:,.0f}"}), width="stretch")
    st.caption("Reduced cost: how much the profit changes per batch pushed beyond the plan. A product not made needs "
               "its contribution to rise by at least −(reduced cost) to enter the plan.")
with right:
    st.subheader("The resources")
    res = pd.DataFrame({"available": cap1, "used": [a - s for a, s in zip(cap1, after["slack"])],
                        "slack": after["slack"], "shadow price (SAR/h)": after["price"]},
                       index=[label for label in HOURS.values()])
    st.dataframe(res.style.format("{:,.1f}"), width="stretch")
    st.caption("Shadow price: what one more hour adds to the best profit. A resource with slack is worth 0.")

st.subheader("Each offer alone")
rows = []
for _, o in options.iterrows():
    cap2, dem2 = list(cap0), dict(dem0)
    if o["adds_to"].startswith("max_batches:"):
        p = o["adds_to"].split(":")[1]
        dem2[p] += o["amount"]
        unit = before["dj"][names.index(p)] if before["plan"][names.index(p)] >= dem0[p] - 1e-6 else 0.0
    else:
        j = list(HOURS).index(o["adds_to"])
        cap2[j] += o["amount"]
        unit = before["price"][j]
    gain = solve(c_t, tuple(dem2[p] for p in names), tuple(cap2))["profit"] - before["profit"]
    rows.append({"offer": o["option"], "cost": o["weekly_cost_sar"], "shadow price × amount": max(unit, 0) * o["amount"],
                 "re-solved gain": gain, "net (re-solved)": gain - o["weekly_cost_sar"]})
fmt = {"cost": "{:,.0f}", "shadow price × amount": "{:,.0f}", "re-solved gain": "{:,.0f}", "net (re-solved)": "{:+,.0f}"}
st.dataframe(pd.DataFrame(rows).set_index("offer").style.format(fmt), width="stretch")
st.caption("When the two columns differ, the change goes beyond the range where the shadow price holds. "
           "Offers can also interact: tick several in the sidebar to see their combined effect.")

st.subheader("Sweep one resource")
r_label = st.selectbox("Resource", list(HOURS.values()), index=2)
j = list(HOURS.values()).index(r_label)
top = int(max(cap1[j] * 2, 10))
values = list(range(0, top + 1, max(1, top // 120)))
curve = []
for v in values:
    cap3 = list(cap1)
    cap3[j] = float(v)
    curve.append(solve(c_t, tuple(dem1[p] for p in names), tuple(cap3))["profit"])
sweep = pd.DataFrame({"best profit (SAR)": curve}, index=pd.Index(values, name=f"{r_label} hours"))
sweep["value of one more hour (SAR)"] = sweep["best profit (SAR)"].diff() / sweep.index.to_series().diff()
a, b = st.columns(2)
a.line_chart(sweep["best profit (SAR)"], x_label=f"{r_label} hours per week", y_label="best weekly profit (SAR)")
b.line_chart(sweep["value of one more hour (SAR)"], x_label=f"{r_label} hours per week", y_label="value of one more hour (SAR)")
st.caption(f"Your scenario has {cap1[j]:g} {r_label} hours. The value of one more hour is the shadow price; "
           "it holds on each flat step and drops where another constraint starts to bind.")
