#!/usr/bin/env python3
"""Saguaro Street Coffee dashboard, built live.

Reads the till export (sales_export.csv), cleans it, does all the math,
checks that the totals add up, and writes one self-contained HTML page.
Same input, same output. Needs only Python 3 and pandas.

Usage:
    python3 saguaro_dashboard.py [path/to/sales_export.csv] [path/to/dashboard.html]

With no arguments it looks for sales_export.csv next to this file, then in
the current folder, and writes dashboard.html to the current folder.
The Colab notebook saguaro_dashboard.ipynb runs this same code, step by step.
"""
import html
import math
import re
import sys
import warnings
from pathlib import Path

import pandas as pd

# Some pandas and NumPy versions print a harmless notice about date math.
# Hide it so the output stays readable in a live demo.
warnings.filterwarnings("ignore", category=DeprecationWarning)

HERE = Path(__file__).resolve().parent if "__file__" in globals() else Path.cwd()
DEFAULT_IN = next((p for p in (HERE / "sales_export.csv", Path.cwd() / "sales_export.csv") if p.exists()),
                  HERE / "sales_export.csv")
DEFAULT_OUT = Path.cwd() / "dashboard.html"
SHOP_NAME = "Saguaro Street Coffee"

# ---------------------------------------------------------------------------
# Product list. Staff type some names by hand, so many spellings point to one
# product. Keys are lower case with spaces, dashes and other marks removed.
# ---------------------------------------------------------------------------
PRODUCTS = {
    "latte": "Latte",
    "icedlatte": "Iced latte",
    "lavenderoatlatte": "Lavender oat latte",
    "cappuccino": "Cappuccino",
    "mocha": "Mocha",
    "americano": "Americano",
    "drip": "Drip coffee",
    "dripcoffee": "Drip coffee",
    "coldbrew": "Cold brew",
    "chailatte": "Chai latte",
    "pricklypearlemonade": "Prickly pear lemonade",
    "pricklypearlemonaid": "Prickly pear lemonade",
    "blueberrymuffin": "Blueberry muffin",
    "croissant": "Croissant",
    "glutenfreescone": "Gluten-free scone",
    "breakfastburrito": "Breakfast burrito",
    "bfastburrito": "Breakfast burrito",
    "avocadotoast": "Avocado toast",
}
CATEGORIES = {"Coffee": "Coffee", "Food": "Food", "Tea": "Tea", "Other Drinks": "Other drinks"}
COLUMNS = {
    "Date": "date", "Time": "time", "Transaction ID": "txn", "Category": "category_raw",
    "Item": "item", "Qty": "qty", "Gross Sales": "gross", "Discount Name": "discount_name",
    "Discounts": "discount", "Net Sales": "net", "Customer ID": "customer_id",
    "Customer Name": "customer_name", "Employee": "employee", "Event Type": "line_type",
}
COMPARE_WEEKS = 13  # the top tiles compare the last 13 weeks with the same weeks a year earlier


def money_to_float(s):
    return pd.to_numeric(s.str.strip().str.replace(r"[\$,]", "", regex=True), errors="coerce")


def key(name):
    return "".join(ch for ch in str(name).lower() if ch.isalnum())


def stated_rate(name):
    """The discount a name promises: 'Happy Hour 20%' is 20%, a comp is 100%."""
    m = re.search(r"(\d+(?:\.\d+)?)\s*%", str(name))
    if m:
        return float(m.group(1)) / 100
    return 1.0 if "comp" in str(name).lower() else None


# ---------------------------------------------------------------------------
# Load and clean
# ---------------------------------------------------------------------------
def load(path):
    raw = pd.read_csv(path, dtype=str, keep_default_na=False)
    d = raw.rename(columns=COLUMNS).copy()
    for c in d.columns:
        d[c] = d[c].str.strip()
    # Customer names are not needed for any number on the dashboard.
    d = d.drop(columns=["customer_name"])
    # The till writes two of the same item as one line with a quantity of 2.
    # So a second line that matches the first to the second, on the same
    # receipt, is the same sale saved twice. Remove the extra copy.
    before = len(d)
    d = d.drop_duplicates().reset_index(drop=True)
    log = {"rows_in": len(raw), "double_saved": before - len(d)}
    for c in ["gross", "discount", "net"]:
        d[c] = money_to_float(d[c])
    d["qty"] = pd.to_numeric(d["qty"], errors="coerce")
    d["day"] = pd.to_datetime(d["date"], format="%m/%d/%Y", errors="coerce")
    d["hour"] = pd.to_numeric(d["time"].str[:2], errors="coerce")
    # Blank means unknown. Keep it as unknown, never guess.
    d["customer_id"] = d["customer_id"].replace("", pd.NA)
    d["discount_name"] = d["discount_name"].replace("", pd.NA)
    d["product"] = [PRODUCTS.get(key(s), s) for s in d["item"]]
    d["category"] = d["category_raw"].map(CATEGORIES).fillna(d["category_raw"])
    log["renamed"] = int((d["item"].map(key) != d["product"].map(key)).sum())
    log["rows_out"] = len(d)
    return raw, d, log


# ---------------------------------------------------------------------------
# Math
# ---------------------------------------------------------------------------
def period_stats(money, start, end):
    m = money[(money["day"] >= start) & (money["day"] < end)]
    pay = m[m["line_type"] == "Payment"]
    ref = m[m["line_type"] == "Refund"]
    sales = m["net"].sum()
    count = pay["txn"].nunique()
    days = (end - start).days
    return {
        "sales": sales,
        "count": count,
        "avg": sales / count if count else 0.0,
        "refunds": -ref["net"].sum(),
        "refund_lines": len(ref),
        "discounts": -pay["discount"].sum(),
        "days": days,
        "weeks": days / 7,
    }


def find_price_change(pay):
    """First day the regular price of the products went up."""
    p = pay.assign(unit=pay["gross"] / pay["qty"]).sort_values("day")
    first_price = p.groupby("product")["unit"].first()
    rises = []
    for prod, g in p.groupby("product"):
        up = g[g["unit"] > first_price[prod] + 0.001]
        if len(up):
            rises.append(up["day"].min())
    if not rises:
        return None, 0
    day = pd.Series(rises).mode().iloc[0]
    return day, sum(1 for r in rises if r == day)


def compute(d):
    data_start = d["day"].min()
    data_end = d["day"].max()
    week0 = data_start - pd.Timedelta(days=int(data_start.weekday()))
    d["week"] = ((d["day"] - week0).dt.days // 7).astype(int)
    d["week_start"] = week0 + pd.to_timedelta(d["week"] * 7, unit="D")

    money = d[d["line_type"] != "Void"].copy()  # a voided sale is never money
    pay = money[money["line_type"] == "Payment"]
    ref = money[money["line_type"] == "Refund"]
    total_sales = money["net"].sum()
    total_count = pay["txn"].nunique()

    # Weeks
    weekly = pd.DataFrame({
        "sales": money.groupby("week_start")["net"].sum(),
        "count": pay.groupby("week_start")["txn"].nunique(),
        "refund_lines": ref.groupby("week_start").size(),
        "discounts": -pay.groupby("week_start")["discount"].sum(),
        "days": d.groupby("week_start")["day"].nunique(),
    }).fillna(0).sort_index()
    weekly["avg"] = weekly["sales"] / weekly["count"]
    full_weeks = weekly[weekly["days"] == 7]

    # Top tiles: the last 13 full weeks against the same 13 weeks a year
    # earlier, so the season is the same on both sides.
    last = full_weeks.index[-COMPARE_WEEKS:]
    now_start, now_end = last[0], last[-1] + pd.Timedelta(days=7)
    yr_start, yr_end = now_start - pd.Timedelta(days=364), now_end - pd.Timedelta(days=364)
    now = period_stats(money, now_start, now_end)
    year_ago = period_stats(money, yr_start, yr_end)

    # Price change: from that day to the end, against the same days a year earlier
    price_day, n_products_up = find_price_change(pay)
    price = None
    if price_day is not None:
        a_start, a_end = price_day, data_end + pd.Timedelta(days=1)
        b_start, b_end = a_start - pd.Timedelta(days=364), a_end - pd.Timedelta(days=364)
        before_p = pay[(pay["day"] >= price_day - pd.Timedelta(days=91)) & (pay["day"] < price_day)]
        after_p = pay[(pay["day"] >= price_day) & (pay["day"] < price_day + pd.Timedelta(days=91))]
        old_u = (before_p["gross"] / before_p["qty"]).groupby(before_p["product"]).median()
        new_u = (after_p["gross"] / after_p["qty"]).groupby(after_p["product"]).median()
        units = before_p.groupby("product")["qty"].sum()
        common = old_u.index.intersection(new_u.index)
        price = {
            "day": price_day,
            "products": n_products_up,
            "rise": (units[common] * new_u[common]).sum() / (units[common] * old_u[common]).sum() - 1,
            "after": period_stats(money, a_start, a_end),
            "year_before": period_stats(money, b_start, b_end),
            "a_start": a_start, "a_end": a_end,
        }

    # Discounts: when each one ran, what it gave away, and which are new
    disc = pay[pay["discount_name"].notna()]
    discounts = pd.DataFrame({
        "first": disc.groupby("discount_name")["day"].min(),
        "last": disc.groupby("discount_name")["day"].max(),
        "uses": disc.groupby("discount_name")["txn"].nunique(),
        "given": -disc.groupby("discount_name")["discount"].sum(),
    }).sort_values("given", ascending=False)
    discounts["new"] = discounts["first"] > data_start + pd.Timedelta(days=28)

    # The biggest new discount that is still running, and the hours it covers
    promo = None
    running = discounts[discounts["new"] & (discounts["last"] >= data_end - pd.Timedelta(days=14))]
    if len(running):
        name = running["given"].idxmax()
        rows = disc[disc["discount_name"] == name]
        hours = sorted(rows["hour"].value_counts().loc[lambda s: s >= 0.05 * len(rows)].index)
        p_start = discounts.loc[name, "first"]
        span = min((p_start - data_start).days, (data_end - p_start).days + 1, 91)
        b0, b1 = p_start - pd.Timedelta(days=span), p_start
        a0, a1 = p_start, p_start + pd.Timedelta(days=span)

        def visits_by_hour(start, end):
            p = pay[(pay["day"] >= start) & (pay["day"] < end)]
            return p.groupby("hour")["txn"].nunique() / (end - start).days

        before_h = visits_by_hour(b0, b1)
        after_h = visits_by_hour(a0, a1)
        last_b = visits_by_hour(b0 - pd.Timedelta(days=364), b1 - pd.Timedelta(days=364))
        last_a = visits_by_hour(a0 - pd.Timedelta(days=364), a1 - pd.Timedelta(days=364))
        inside = before_h.index.isin(hours)

        def sales_in_hours(start, end):
            m = money[(money["day"] >= start) & (money["day"] < end) & money["hour"].isin(hours)]
            return m["net"].sum() / (end - start).days

        promo = {
            "name": name,
            "start": p_start,
            "hours": hours,
            "given": float(discounts.loc[name, "given"]),
            "uses": int(discounts.loc[name, "uses"]),
            "days": span,
            "b0": b0, "b1": b1, "a0": a0, "a1": a1,
            "before_h": before_h, "after_h": after_h,
            "in_before": before_h[inside].sum(), "in_after": after_h.reindex(hours).fillna(0).sum(),
            "out_before": before_h[~inside].sum(), "out_after": after_h[~after_h.index.isin(hours)].sum(),
            "in_sales_before": sales_in_hours(b0, b1), "in_sales_after": sales_in_hours(a0, a1),
            "given_per_day": -rows[(rows["day"] >= a0) & (rows["day"] < a1)]["discount"].sum() / span,
            "given_now": -rows[(rows["day"] >= now_start) & (rows["day"] < now_end)]["discount"].sum(),
            "in_last_chg": change(last_a.reindex(hours).fillna(0).sum(), last_b.reindex(hours).fillna(0).sum()),
            "out_last_chg": change(last_a[~last_a.index.isin(hours)].sum(), last_b[~last_b.index.isin(hours)].sum()),
        }

    # Refunds: find the week where one item was refunded far more than usual
    spike = None
    rw = ref.groupby(["week_start", "product"]).size().unstack(fill_value=0).reindex(full_weeks.index, fill_value=0)
    if len(rw):
        typical = rw.median()
        jump = rw - typical
        week, prod = jump.stack().idxmax()
        count = int(rw.loc[week, prod])
        if count >= 5 and count >= 3 * max(typical[prod], 1):
            others = rw[prod].drop(week)
            sold = pay[(pay["week_start"] == week) & (pay["product"] == prod)]["qty"].sum()
            sold_typical = pay[pay["product"] == prod].groupby("week_start")["qty"].sum().median()
            wref = ref[(ref["week_start"] == week) & (ref["product"] == prod)]
            spike = {
                "week": week,
                "product": prod,
                "count": count,
                "typical_week": float(others.mean()),
                "max_other": int(others.max()),
                "dollars": float(-wref["net"].sum()),
                "sold": int(sold),
                "sold_typical": float(sold_typical),
                "staff": int(wref["employee"].nunique()),
                "days": int(wref["day"].nunique()),
            }
    refund_weeks = rw.sum(axis=1)

    # Items and categories over the whole file
    by_item = money.groupby("product")["net"].sum().sort_values(ascending=False)
    by_cat = money.groupby("category")["net"].sum().sort_values(ascending=False)

    return {
        "d": d, "money": money, "weekly": weekly, "full_weeks": full_weeks,
        "data_start": data_start, "data_end": data_end,
        "total_sales": total_sales, "total_count": total_count,
        "now": now, "year_ago": year_ago,
        "now_start": now_start, "now_end": now_end, "yr_start": yr_start, "yr_end": yr_end,
        "price": price, "discounts": discounts, "promo": promo,
        "spike": spike, "refund_weeks": refund_weeks, "refund_by_item": rw,
        "by_item": by_item, "by_cat": by_cat,
    }


# ---------------------------------------------------------------------------
# Checks: the totals must add up before anything is shown
# ---------------------------------------------------------------------------
def run_checks(d, R):
    checks = []
    money, weekly = R["money"], R["weekly"]

    def add(ok, plain):
        checks.append((bool(ok), plain))

    add(d["day"].notna().all(), "Every row has a date the code can read.")
    add(d[["gross", "discount", "net", "qty"]].notna().all().all(), "Every row has amounts the code can read.")
    add(d["line_type"].isin(["Payment", "Refund", "Void"]).all(), "Every row is a payment, a refund or a voided sale.")
    add(((d["net"].abs() - (d["gross"].abs() - d["discount"].abs())).abs() < 0.005).all(),
        "On every row, the line amount minus the discount equals the amount charged.")
    rate = d["discount_name"].map(stated_rate)
    named = d[d["discount_name"].notna()]
    add(rate[named.index].notna().all()
        and ((named["discount"].abs() - rate[named.index] * named["gross"].abs()).abs() <= 0.011).all(),
        "Every discount matches the rate in its name, to the cent.")
    pay = d[d["line_type"] == "Payment"]
    ref = d[d["line_type"] == "Refund"]
    add((pay["net"] >= 0).all() and (ref["net"] <= 0).all(), "Payments are money in and refunds are money out.")
    k = ["txn", "product"]
    matched = ref.merge(pay[k].drop_duplicates(), on=k, how="left", indicator=True)
    add((matched["_merge"] == "both").all(), "Every refund points back to a sale of that item on the same receipt.")
    add(not money["line_type"].eq("Void").any(), "No voided sale is counted as money.")
    add(abs(weekly["sales"].sum() - R["total_sales"]) < 0.01, "The weeks add up to the total sales.")
    add(abs(R["by_cat"].sum() - R["total_sales"]) < 0.01, "The categories add up to the total sales.")
    add(abs(R["by_item"].sum() - R["total_sales"]) < 0.01, "The items add up to the total sales.")
    add(weekly["count"].sum() == R["total_count"], "The weekly counts add up to the total number of sales.")
    return checks


# ---------------------------------------------------------------------------
# Formatting helpers
# ---------------------------------------------------------------------------
def usd(x, cents=False):
    return f"${x:,.2f}" if cents else f"${x:,.0f}"


def pct(x):
    return f"{abs(x) * 100:.0f}%"


def day_label(ts):
    return f"{ts.strftime('%b')} {ts.day}"


def day_label_year(ts):
    return f"{ts.strftime('%b')} {ts.day}, {ts.year}"


def change(a, b):
    return (a - b) / b if b else 0.0


def esc(s):
    return html.escape(str(s), quote=True)


def round_to(x, step):
    return int(round(x / step) * step)


# ---------------------------------------------------------------------------
# Charts (inline SVG)
# ---------------------------------------------------------------------------
W = 400  # every chart is drawn on a 400-wide canvas and scales to fit


def nice_max(v):
    if v <= 0:
        return 1
    mag = 10 ** math.floor(math.log10(v))
    for m in (1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10):
        if m * mag >= v:
            return m * mag
    return 10 * mag


def short_money(v):
    if v >= 1000:
        k = v / 1000
        return f"${k:.0f}K" if abs(k - round(k)) < 0.05 else f"${k:.1f}K"
    return f"${v:.0f}"


def bar_path(x, y, w, h, r=4):
    """Vertical bar, rounded top, square bottom."""
    if h <= 0:
        return ""
    r = min(r, w / 2, h)
    return (f"M{x:.1f},{y + h:.1f} V{y + r:.1f} Q{x:.1f},{y:.1f} {x + r:.1f},{y:.1f} "
            f"H{x + w - r:.1f} Q{x + w:.1f},{y:.1f} {x + w:.1f},{y + r:.1f} V{y + h:.1f} Z")


def nice_ticks(lo, hi, n=4):
    """Axis lines at tidy steps (1, 2, 2.5 or 5 times a power of ten) that cover lo to hi."""
    span = (hi - lo) or abs(hi) or 1
    mag = 10 ** math.floor(math.log10(span / n))
    step = next(m * mag for m in (1, 2, 2.5, 5, 10) if span / (m * mag) <= n)
    first, last = math.floor(lo / step + 1e-9), math.ceil(hi / step - 1e-9)
    return [k * step for k in range(first, last + 1)]


def hour_label(h):
    h = int(h)
    return f"{h % 12 or 12} {'AM' if h < 12 else 'PM'}"


def week_x(day, first_week, left, pw, n):
    """Where a day falls along a line of weekly points."""
    return left + pw * ((day - first_week).days / 7) / (n - 1)


def short_name(name):
    """'Happy Hour 20%' becomes 'Happy Hour'."""
    return re.sub(r"\s*\d+(\.\d+)?\s*%$", "", str(name)).strip()


def markers(R):
    out = []
    if R["price"]:
        out.append((R["price"]["day"], "Prices up"))
    if R["promo"]:
        out.append((R["promo"]["start"], short_name(R["promo"]["name"]) + " starts"))
    return out


def chart_weekly(R):
    """Sales each week over the whole file, with the price rise and the new discount marked."""
    wk = R["full_weeks"]["sales"]
    Wd, H = 800, 260
    left, right, top, bottom = 52, 12, 34, 30
    pw, ph = Wd - left - right, H - top - bottom
    ticks = nice_ticks(wk.min(), wk.max())
    lo, hi = ticks[0], ticks[-1]
    n = len(wk)
    first = wk.index[0]

    def y(v):
        return top + ph - ph * (v - lo) / (hi - lo)

    out = [f'<svg viewBox="0 0 {Wd} {H}" role="img" aria-label="Weekly sales line chart">']
    for v in ticks:
        out.append(f'<line class="grid" x1="{left}" x2="{Wd - right}" y1="{y(v):.1f}" y2="{y(v):.1f}"/>')
        out.append(f'<text class="tick" x="{left - 6}" y="{y(v) + 4:.1f}" text-anchor="end">{short_money(v)}</text>')
    for day, label in markers(R):
        x = week_x(day, first, left, pw, n)
        out.append(f'<line class="marker" x1="{x:.1f}" x2="{x:.1f}" y1="{top - 12}" y2="{top + ph}"/>')
        out.append(f'<text class="note" x="{x + 4:.1f}" y="{top - 4}">{esc(label)}</text>')
    pts = [(left + pw * i / (n - 1), y(v)) for i, v in enumerate(wk.values)]
    out.append(f'<path class="line1" d="M{" L".join(f"{a:.1f},{b:.1f}" for a, b in pts)}"/>')
    for (px, py), (ws, v) in zip(pts, wk.items()):
        out.append(f'<g><title>Week of {esc(day_label_year(ws))}: {esc(usd(v))}</title>'
                   f'<circle class="hitdot" cx="{px:.1f}" cy="{py:.1f}" r="5"/></g>')
    out.append(f'<circle class="dot1" cx="{pts[-1][0]:.1f}" cy="{pts[-1][1]:.1f}" r="4"/>')
    for i, ws in enumerate(wk.index):
        # label the first week of each quarter
        if ws.month in (1, 4, 7, 10) and ws.day <= 7:
            x = left + pw * i / (n - 1)
            out.append(f'<text class="tick" x="{x:.1f}" y="{H - 8}" text-anchor="middle">{ws.strftime("%b %Y")}</text>')
    out.append(f'<line class="axis" x1="{left}" x2="{Wd - right}" y1="{top + ph}" y2="{top + ph}"/>')
    out.append("</svg>")
    return "".join(out)


def mini_line(series, label_fmt, title, R, H=170):
    left, right, top, bottom = 52, 10, 26, 24
    width = W / 2 - 6
    pw, ph = width - left - right, H - top - bottom
    ticks = nice_ticks(series.min(), series.max(), 3)
    lo, hi = ticks[0], ticks[-1]
    n = len(series)
    first = series.index[0]

    def y(v):
        return top + ph - ph * (v - lo) / (hi - lo)

    out = [f'<svg viewBox="0 0 {width:.0f} {H}" role="img" aria-label="{esc(title)}">',
           f'<text class="label" x="0" y="12">{esc(title)}</text>']
    for v in ticks:
        out.append(f'<line class="grid" x1="{left}" x2="{width - right}" y1="{y(v):.1f}" y2="{y(v):.1f}"/>')
        out.append(f'<text class="tick" x="{left - 5}" y="{y(v) + 4:.1f}" text-anchor="end">{label_fmt(v)}</text>')
    for day, _ in markers(R):
        x = week_x(day, first, left, pw, n)
        out.append(f'<line class="marker" x1="{x:.1f}" x2="{x:.1f}" y1="{top}" y2="{top + ph}"/>')
    pts = [(left + pw * i / (n - 1), y(v)) for i, v in enumerate(series.values)]
    out.append(f'<path class="line1" d="M{" L".join(f"{a:.1f},{b:.1f}" for a, b in pts)}"/>')
    for (px, py), (ws, v) in zip(pts, series.items()):
        out.append(f'<g><title>Week of {esc(day_label_year(ws))}: {esc(label_fmt(v, True))}</title>'
                   f'<circle class="hitdot" cx="{px:.1f}" cy="{py:.1f}" r="4"/></g>')
    out.append(f'<circle class="dot1" cx="{pts[-1][0]:.1f}" cy="{pts[-1][1]:.1f}" r="3.5"/>')
    out.append(f'<text class="tick" x="{left}" y="{H - 6}">{series.index[0].strftime("%b %Y")}</text>')
    out.append(f'<text class="tick" x="{width - right}" y="{H - 6}" text-anchor="end">{series.index[-1].strftime("%b %Y")}</text>')
    out.append("</svg>")
    return "".join(out)


def chart_count_and_avg(R):
    fw = R["full_weeks"]
    a = mini_line(fw["count"], lambda v, full=False: f"{v:,.0f}", "Sales a week", R)
    b = mini_line(fw["avg"], lambda v, full=False: usd(v, True), "Average sale", R)
    return f'<div class="pair">{a}{b}</div>'


def chart_hours(R):
    """Visits a day in each hour, before and after the new discount started."""
    P = R["promo"]
    hours = sorted(set(P["before_h"].index) | set(P["after_h"].index))
    b = P["before_h"].reindex(hours).fillna(0)
    a = P["after_h"].reindex(hours).fillna(0)
    H = 250
    left, right, top, bottom = 34, 8, 24, 30
    pw, ph = W - left - right, H - top - bottom
    ticks = nice_ticks(0, max(b.max(), a.max()))
    vmax = ticks[-1]
    slot = pw / len(hours)
    bw = min(14, (slot - 8) / 2)
    out = [f'<svg viewBox="0 0 {W} {H}" role="img" aria-label="Visits by hour of day, before and after">']
    for i, h in enumerate(hours):
        if h in P["hours"]:
            x = left + i * slot
            out.append(f'<rect class="band" x="{x:.1f}" y="{top}" width="{slot:.1f}" height="{ph}"/>')
    hh = [i for i, h in enumerate(hours) if h in P["hours"]]
    if hh:
        x = left + (hh[0] + (hh[-1] + 1)) / 2 * slot
        out.append(f'<text class="note" x="{x:.1f}" y="{top - 8}" text-anchor="middle">{esc(short_name(P["name"]))}</text>')
    for v in ticks:
        yy = top + ph - ph * v / vmax
        out.append(f'<line class="grid" x1="{left}" x2="{W - right}" y1="{yy:.1f}" y2="{yy:.1f}"/>')
        out.append(f'<text class="tick" x="{left - 6}" y="{yy + 4:.1f}" text-anchor="end">{v:.0f}</text>')
    for i, h in enumerate(hours):
        x0 = left + i * slot + (slot - 2 * bw - 2) / 2
        for j, (cls, v, when) in enumerate((("sb", b[h], "Before"), ("s1", a[h], "After"))):
            hgt = ph * v / vmax
            x = x0 + j * (bw + 2)
            out.append(f'<g><title>{esc(hour_label(h))}, {when.lower()}: {v:.1f} visits a day</title>'
                       f'<path class="{cls}" d="{bar_path(x, top + ph - hgt, bw, hgt, 3)}"/></g>')
        out.append(f'<text class="tick" x="{left + i * slot + slot / 2:.1f}" y="{H - bottom + 16}" '
                   f'text-anchor="middle">{esc(hour_label(h))}</text>')
    out.append(f'<line class="axis" x1="{left}" x2="{W - right}" y1="{top + ph}" y2="{top + ph}"/>')
    out.append("</svg>")
    legend = (f'<div class="legend"><span><i class="kb"></i>{P["days"] // 7} weeks before</span>'
              f'<span><i class="k1"></i>{P["days"] // 7} weeks after</span></div>')
    return legend + "".join(out)


def chart_refunds(R, weeks=26):
    """Refunds each week for the last half year, with the problem item in orange."""
    rw = R["refund_by_item"].tail(weeks)
    S = R["spike"]
    spike_item = S["product"] if S else None
    hot = rw[spike_item] if spike_item else pd.Series(0, index=rw.index)
    rest = rw.sum(axis=1) - hot
    H = 250
    left, right, top, bottom = 34, 8, 16, 30
    pw, ph = W - left - right, H - top - bottom
    ticks = nice_ticks(0, (rest + hot).max())
    vmax = ticks[-1]
    slot = pw / len(rw)
    bw = min(12, slot - 3)
    out = [f'<svg viewBox="0 0 {W} {H}" role="img" aria-label="Refunds each week">']
    for v in ticks:
        yy = top + ph - ph * v / vmax
        out.append(f'<line class="grid" x1="{left}" x2="{W - right}" y1="{yy:.1f}" y2="{yy:.1f}"/>')
        out.append(f'<text class="tick" x="{left - 6}" y="{yy + 4:.1f}" text-anchor="end">{v:.0f}</text>')
    for i, ws in enumerate(rw.index):
        x = left + i * slot + (slot - bw) / 2
        h_rest = ph * rest[ws] / vmax
        h_hot = ph * hot[ws] / vmax
        y_rest = top + ph - h_rest
        tip = f"Week of {day_label_year(ws)}: {int(rest[ws] + hot[ws])} refunds"
        if spike_item:
            tip += f", {int(hot[ws])} of them {spike_item.lower()}"
        out.append(f'<g><title>{esc(tip)}</title>')
        if h_hot > 0:
            out.append(f'<path class="s1" d="{bar_path(x, y_rest, bw, h_rest, 0)}"/>')
            out.append(f'<path class="s2" d="{bar_path(x, y_rest - h_hot, bw, max(h_hot - 1.5, 0.5), 3)}"/>')
        else:
            out.append(f'<path class="s1" d="{bar_path(x, y_rest, bw, h_rest, 3)}"/>')
        out.append(f'<rect class="hit" x="{left + i * slot:.1f}" y="{top}" width="{slot:.1f}" height="{ph}"/></g>')
        if (len(rw) - 1 - i) % 6 == 0:
            out.append(f'<text class="tick" x="{x + bw / 2:.1f}" y="{H - bottom + 16}" text-anchor="middle">{day_label(ws)}</text>')
    out.append(f'<line class="axis" x1="{left}" x2="{W - right}" y1="{top + ph}" y2="{top + ph}"/>')
    out.append("</svg>")
    legend = '<div class="legend"><span><i class="k1"></i>Other items</span>'
    if spike_item:
        legend += f'<span><i class="k2"></i>{esc(spike_item.capitalize())}</span>'
    return legend + "</div>" + "".join(out)


# ---------------------------------------------------------------------------
# Words. Every number below comes from the math above.
# ---------------------------------------------------------------------------
def fewer_more(x, fewer="fewer", more="more"):
    return f"{pct(x)} {fewer if x < 0 else more}"


def up_down(x, band=0.01):
    if abs(x) < band:
        return "about the same"
    return f"{'up' if x > 0 else 'down'} {pct(x)}"


def titles(R):
    now, yr = R["now"], R["year_ago"]
    ch = change(now["sales"], yr["sales"])
    t1 = (f"Weekly sales are {up_down(ch)} from the same weeks last year"
          if abs(ch) >= 0.01 else "Weekly sales match the same weeks last year")

    t2 = "Sales a week and the average sale"
    if R["price"]:
        p = R["price"]
        cnt = change(p["after"]["count"], p["year_before"]["count"])
        avg = change(p["after"]["avg"], p["year_before"]["avg"])
        t2 = (f"Since prices went up: {fewer_more(cnt)} sales than a year earlier, "
              f"each one {fewer_more(avg, 'smaller', 'bigger')}")

    t3 = ""
    if R["promo"]:
        P = R["promo"]
        when = "afternoon" if min(P["hours"]) >= 12 else "morning" if max(P["hours"]) < 12 else "discount-hour"
        t3 = (f"Since {short_name(P['name'])} started: {fewer_more(change(P['in_after'], P['in_before']))} {when} visits, "
              f"{fewer_more(change(P['out_after'], P['out_before']))} the rest of the day")

    S = R["spike"]
    t4 = (f"{S['product']} refunds jumped to {S['count']} in the week of {day_label(S['week'])}"
          if S else "Refunds stayed in their usual range")
    return t1, t2, t3, t4


def what_this_means(R):
    now, yr, P, S, price = R["now"], R["year_ago"], R["promo"], R["spike"], R["price"]

    says = []
    p1 = (f"Over the last {now['weeks']:.0f} weeks the shop took in {usd(now['sales'])}, "
          f"against {usd(yr['sales'])} in the same weeks last year. That is {up_down(change(now['sales'], yr['sales']))}. "
          f"It made {now['count']:,} sales, {fewer_more(change(now['count'], yr['count']))} than a year earlier, "
          f"and the average sale was {usd(now['avg'], True)}, {up_down(change(now['avg'], yr['avg']))}. ")
    if now["count"] < yr["count"] and now["avg"] > yr["avg"]:
        p1 += "Fewer people are coming in, and the bigger average sale only covers part of the gap."
    says.append(p1)

    if price:
        a, b = price["after"], price["year_before"]
        says.append(
            f"Prices went up on {day_label_year(price['day'])}, by about {pct(price['rise'])} on average across "
            f"{price['products']} items. Since then, sales are {up_down(change(a['sales'], b['sales']))} on the same days "
            f"a year earlier, the number of sales is {up_down(change(a['count'], b['count']))}, "
            f"and the average sale is {up_down(change(a['avg'], b['avg']))}. "
            f"Possibly because some regulars now come in less often at the higher prices."
        )

    if P:
        hrs = f"{hour_label(P['hours'][0])} and {hour_label(P['hours'][-1])}" if len(P["hours"]) > 1 else hour_label(P["hours"][0])
        says.append(
            f"{short_name(P['name'])} started on {day_label_year(P['start'])}, with "
            f"{pct(stated_rate(P['name'])) + ' off' if stated_rate(P['name']) else 'a discount on'} "
            f"sales in the {hrs} hours. "
            f"So far it has given {usd(P['given'])} off across {P['uses']:,} sales. "
            + (f"In the last {now['weeks']:.0f} weeks it gave {usd(P['given_now'])} off, "
               "which is most of the rise in discounts on the tiles. "
               if P["given_now"] >= 0.5 * (now["discounts"] - yr["discounts"]) > 0 else "")
            + f"In the {P['days'] // 7} weeks after it started, visits in those hours went from "
            f"{P['in_before']:.1f} to {P['in_after']:.1f} a day, while visits in the rest of the day went from "
            f"{P['out_before']:.0f} to {P['out_after']:.0f}. "
            f"In the same weeks last year, those hours were {up_down(P['in_last_chg'])} and the rest of the day "
            f"{up_down(P['out_last_chg'])}. Possibly because some customers who used to come earlier now wait for the discount."
        )

    if S:
        says.append(
            f"Refunds on the {S['product'].lower()} jumped in the week of {day_label_year(S['week'])}: "
            f"{S['count']} refunds worth {usd(S['dollars'], True)}, where a normal week has "
            f"{'none or one' if S['typical_week'] < 1 else 'about ' + str(round(S['typical_week']))} and no other week had more than {S['max_other']}. "
            f"They came on {S['days']} different days from {S['staff']} different staff members, "
            f"so it was not one bad shift. The shop still sold {S['sold']} that week, about the usual {S['sold_typical']:.0f}. "
            f"Possibly because of a bad batch of an ingredient or a change in the recipe."
        )

    read = [
        f"The tiles at the top compare the last {now['weeks']:.0f} weeks "
        f"({day_label(R['now_start'])} to {day_label_year(R['now_end'] - pd.Timedelta(days=1))}) with the same "
        f"{yr['weeks']:.0f} weeks a year earlier, so the season is the same on both sides. "
        "Green means the change is good for the shop and red means it is not. For refunds and discounts, down is good.",
        f"The wide chart shows sales for each of the {len(R['full_weeks'])} weeks in the file. "
        "The thin lines mark the price rise and the start of the new discount.",
        "The two small charts split those sales into how many sales the shop made each week and how big each one was.",
    ]
    if P:
        read.append(
            "The hour chart shows the average number of visits a day in each hour of the day. "
            f"Light bars are the {P['days'] // 7} weeks before {short_name(P['name'])} started and dark bars are the "
            f"{P['days'] // 7} weeks after. The shaded hours are when the discount runs."
        )
    read.append("The refund chart counts refunds each week for the last 26 weeks"
                + (f", with the {S['product'].lower()} in orange." if S else "."))

    nxt = []
    if S:
        nxt.append(
            f"Ask the kitchen what changed with the {S['product'].lower()} in the week of {day_label(S['week'])}, "
            "and check that week's ingredients and recipe. Refunds on a top seller can cost regulars as well as money."
        )
    if P:
        nxt.append(
            f"Decide whether {short_name(P['name'])} pays for itself. Sales in those hours went from {usd(P['in_sales_before'])} "
            f"to {usd(P['in_sales_after'])} a day, while the discount gives away about {usd(P['given_per_day'])} a day. "
            "Watch whether morning visits keep falling while it runs."
        )
    return says, read, nxt


# ---------------------------------------------------------------------------
# Page
# ---------------------------------------------------------------------------
CSS = """
:root{
  color-scheme: light;
  --page:#f6f5f1; --card:#fcfcfb; --ink:#1b1b1a; --ink2:#52514e; --muted:#7a7873;
  --grid:#e6e5df; --axis:#c3c2b7; --ring:rgba(11,11,11,0.08);
  --s1:#2a78d6; --s2:#eb6834; --sb:#9ec5f4; --band:rgba(42,120,214,0.07);
  --good:#006300; --bad:#b42b2b;
}
@media (prefers-color-scheme: dark){
  :root:not([data-theme="light"]){
    color-scheme: dark;
    --page:#0f0f0e; --card:#1a1a19; --ink:#f0efec; --ink2:#c3c2b7; --muted:#9a988f;
    --grid:#2c2c2a; --axis:#45453f; --ring:rgba(255,255,255,0.10);
    --s1:#3987e5; --s2:#d95926; --sb:#1c5cab; --band:rgba(57,135,229,0.10);
    --good:#3fbf3f; --bad:#f07a7a;
  }
}
:root[data-theme="dark"]{
  color-scheme: dark;
  --page:#0f0f0e; --card:#1a1a19; --ink:#f0efec; --ink2:#c3c2b7; --muted:#9a988f;
  --grid:#2c2c2a; --axis:#45453f; --ring:rgba(255,255,255,0.10);
  --s1:#3987e5; --s2:#d95926; --sb:#1c5cab; --band:rgba(57,135,229,0.10);
  --good:#3fbf3f; --bad:#f07a7a;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--page);color:var(--ink);
  font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;overflow-x:hidden}
main{max-width:1120px;margin:0 auto;padding:24px 16px 48px}
header h1{margin:0;font-size:1.6rem;font-weight:650;letter-spacing:-0.01em}
header p{margin:4px 0 0;color:var(--ink2);font-size:.95rem}
.tag{display:inline-block;margin-left:6px;padding:1px 8px;border-radius:999px;border:1px solid var(--ring);
  color:var(--muted);font-size:.8rem;vertical-align:middle}
.period{margin:24px 0 10px;color:var(--ink2);font-size:.9rem}
.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px}
.tile{background:var(--card);border:1px solid var(--ring);border-radius:12px;padding:14px 16px}
.tile .lab{color:var(--ink2);font-size:.88rem}
.tile .num{font-size:1.75rem;font-weight:650;margin:2px 0 4px;letter-spacing:-0.01em}
.tile .chg{font-size:.85rem;font-weight:600}
.tile .chg.good{color:var(--good)} .tile .chg.bad{color:var(--bad)} .tile .chg.flat{color:var(--ink2)}
.tile .was{display:block;color:var(--muted);font-weight:400;font-size:.8rem}
.charts{display:grid;grid-template-columns:1fr;gap:12px;margin-top:20px}
@media (min-width:860px){.charts{grid-template-columns:1fr 1fr}}
.card{background:var(--card);border:1px solid var(--ring);border-radius:12px;padding:16px;min-width:0}
.card h2{margin:0 0 4px;font-size:1.02rem;font-weight:620;line-height:1.35}
.card .sub{margin:0 0 10px;color:var(--ink2);font-size:.86rem}
.card svg{display:block;width:100%;height:auto;max-width:560px;margin:0 auto;overflow:visible}
.pair{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.pair svg{max-width:360px}
.card.wide{grid-column:1/-1}
.card.wide svg{max-width:900px}
.legend{display:flex;flex-wrap:wrap;gap:4px 16px;margin:0 0 8px;color:var(--ink2);font-size:.84rem}
.legend i{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:6px;vertical-align:-1px}
.k1{background:var(--s1)} .k2{background:var(--s2)} .kb{background:var(--sb)}
svg text{font-family:inherit}
.tick{fill:var(--muted);font-size:12px}
.note{fill:var(--ink2);font-size:12px}
.label{fill:var(--ink2);font-size:13px;font-weight:600}
.cat{fill:var(--ink);font-size:12.5px}
.cat.rank-top{font-weight:650}
.cat.rank-low{fill:var(--ink2)}
.val{fill:var(--ink2);font-size:12px}
.grid{stroke:var(--grid);stroke-width:1}
.axis{stroke:var(--axis);stroke-width:1}
.marker{stroke:var(--ink2);stroke-width:1;stroke-dasharray:none;opacity:.6}
.band{fill:var(--band)}
.s1{fill:var(--s1)} .s2{fill:var(--s2)} .sb{fill:var(--sb)}
.line1{fill:none;stroke:var(--s1);stroke-width:2;stroke-linejoin:round;stroke-linecap:round}
.dot1{fill:var(--s1);stroke:var(--card);stroke-width:2}
.hit,.hitdot{fill:transparent}
g:hover .s1,g:hover .s2,g:hover .sb{opacity:.82}
.means{background:var(--card);border:1px solid var(--ring);border-radius:12px;padding:20px;margin-top:20px}
.means h2{margin:0 0 6px;font-size:1.25rem}
.means h3{margin:18px 0 6px;font-size:1rem;color:var(--ink2);font-weight:620}
.means p{margin:0 0 10px;max-width:72ch}
.means ol{margin:0;padding-left:1.3em;max-width:72ch} .means li{margin-bottom:8px}
.stop{background:var(--card);border:1px solid var(--ring);border-radius:12px;padding:20px;margin-top:20px}
@media (max-width:480px){
  header h1{font-size:1.35rem}
  .tile{padding:12px}
  .tile .num{font-size:1.45rem}
  .tiles{grid-template-columns:1fr 1fr}
  .pair{grid-template-columns:1fr}
  .card{padding:14px 12px}
  .means{padding:16px 14px}
}
"""


def tile(label, now, was, chg, up_is_good, fmt, extra=""):
    if abs(chg) < 0.005:
        cls, arrow = "flat", "■"
        word = "No change"
    else:
        good = (chg > 0) == up_is_good
        cls = "good" if good else "bad"
        arrow = "▲" if chg > 0 else "▼"
        word = f"{'Up' if chg > 0 else 'Down'} {pct(chg)}"
    return (f'<div class="tile"><div class="lab">{esc(label)}</div>'
            f'<div class="num">{esc(fmt(now))}</div>'
            f'<div class="chg {cls}">{arrow} {esc(word)}<span class="was">was {esc(fmt(was))}{esc(extra)}</span></div></div>')


def page(R, checks):
    start, end = R["data_start"], R["data_end"]
    head = (f'<header><h1>{esc(SHOP_NAME)} sales</h1>'
            f'<p>{esc(day_label_year(start))} to {esc(day_label_year(end))}<span class="tag">Sample files</span></p></header>')
    failed = [c for ok, c in checks if not ok]
    if failed:
        items = "".join(f"<li>{esc(c)}</li>" for c in failed)
        body = (f'<section class="stop"><h2>The numbers did not add up</h2>'
                f'<p>Before showing anything, the code checks that its totals match. These checks did not pass:</p>'
                f'<ol>{items}</ol><p>No numbers are shown, so nothing here can mislead you. '
                f'Send the file again or ask for help finding the rows that do not match.</p></section>')
        return doc(head + body)

    now, yr = R["now"], R["year_ago"]
    period = (f'<p class="period">The last {now["weeks"]:.0f} weeks '
              f'({esc(day_label(R["now_start"]))} to {esc(day_label_year(R["now_end"] - pd.Timedelta(days=1)))}), '
              f'compared with the same weeks a year earlier</p>')
    tiles = "".join([
        tile("Sales", now["sales"], yr["sales"], change(now["sales"], yr["sales"]), True, usd),
        tile("Number of sales", now["count"], yr["count"], change(now["count"], yr["count"]), True, lambda v: f"{v:,.0f}"),
        tile("Average sale", now["avg"], yr["avg"], change(now["avg"], yr["avg"]), True, lambda v: usd(v, True)),
        tile("Refunds", now["refunds"], yr["refunds"], change(now["refunds"], yr["refunds"]), False, usd),
        tile("Discounts given", now["discounts"], yr["discounts"], change(now["discounts"], yr["discounts"]), False, usd),
    ])
    t1, t2, t3, t4 = titles(R)
    cards = [
        f'<article class="card wide"><h2>{esc(t1)}</h2><p class="sub">Sales each week, after refunds</p>{chart_weekly(R)}</article>',
        f'<article class="card"><h2>{esc(t2)}</h2><p class="sub">Each week. The thin lines mark the price rise and the new discount.</p>{chart_count_and_avg(R)}</article>',
    ]
    if R["promo"]:
        cards.append(f'<article class="card"><h2>{esc(t3)}</h2><p class="sub">Average visits a day in each hour</p>{chart_hours(R)}</article>')
    cards.append(f'<article class="card"><h2>{esc(t4)}</h2><p class="sub">Refunds each week, last 26 weeks</p>{chart_refunds(R)}</article>')
    charts = '<section class="charts">' + "".join(cards) + '</section>'
    says, read, nxt = what_this_means(R)
    means = ('<section class="means"><h2>What this means</h2>'
             '<h3>What the numbers say</h3>' + "".join(f"<p>{esc(p)}</p>" for p in says) +
             '<h3>How to read the charts</h3>' + "".join(f"<p>{esc(p)}</p>" for p in read) +
             '<h3>Worth doing next</h3><ol>' + "".join(f"<li>{esc(p)}</li>" for p in nxt) + '</ol></section>')
    return doc(head + period + f'<section class="tiles">{tiles}</section>' + charts + means)


def doc(inner):
    return ("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">"
            "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
            f"<title>{esc(SHOP_NAME)} Sales</title><style>{CSS}</style></head>"
            f"<body><main>{inner}</main></body></html>\n")


def main():
    src = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_IN
    out = Path(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_OUT
    if not src.exists():
        print(f"Could not find {src}. Put sales_export.csv next to this file, or pass its path.")
        sys.exit(1)
    _, d, log = load(src)
    R = compute(d)
    checks = run_checks(d, R)
    out.write_text(page(R, checks), encoding="utf-8")
    passed = sum(ok for ok, _ in checks)
    print(f"Read {log['rows_in']:,} rows, removed {log['double_saved']:,} saved twice, kept {log['rows_out']:,}")
    print(f"Wrote {out}")
    print(f"Checks passed: {passed} of {len(checks)}")
    for ok, c in checks:
        if not ok:
            print(f"  Did not pass: {c}")


if __name__ == "__main__":
    main()
