"""Side-by-side page of twin results for each fix, with the 1.05 Rule check.

No AI inside. Same file in, same page out, every time.

Usage:
  python3 compare_fixes.py results/fixes.csv --late-cost 1800 --weeks 4 --out results/fixes.html

fixes.csv columns (header on row 1):
  fix,on_time_pct,late_orders_per_run,one_time_cost,cost_per_year
The first row must be the fix named "today" (nothing changed), with costs 0.

The math, all in plain sight:
  late orders saved a year = (today's late orders per run - this fix's) x (52 / weeks)
  money back a year        = late orders saved a year x late cost
  first-year cost          = one_time_cost + cost_per_year
  return per dollar        = money back a year / first-year cost
  1.05 Rule                = passes when each dollar comes back as at least $1.05
                             (a fix that costs nothing passes if it saves anything)
"""
import argparse
import csv
import html
import sys

COLUMNS = ["fix", "on_time_pct", "late_orders_per_run", "one_time_cost", "cost_per_year"]


def stop(message):
    sys.exit(f"STOPPED: {message}")


def number(row, column, line):
    raw = (row.get(column) or "").strip()
    try:
        return float(raw)
    except ValueError:
        stop(f'line {line}: {column} must be a plain number. It says "{raw}".')


def read_fixes(path):
    with open(path, newline="") as handle:
        reader = csv.DictReader(handle)
        missing = [c for c in COLUMNS if c not in (reader.fieldnames or [])]
        if missing:
            stop(f"{path} is missing column(s): {', '.join(missing)}")
        rows = []
        for line, row in enumerate(reader, start=2):
            fix = (row["fix"] or "").strip()
            if not fix:
                stop(f"line {line}: fix name is blank.")
            item = {"fix": fix}
            for column in COLUMNS[1:]:
                item[column] = number(row, column, line)
            if not 0 <= item["on_time_pct"] <= 100:
                stop(f"line {line}: on_time_pct must be 0 to 100. It says {item['on_time_pct']}.")
            if item["late_orders_per_run"] < 0 or item["one_time_cost"] < 0 or item["cost_per_year"] < 0:
                stop(f"line {line}: late orders and costs cannot be below 0.")
            rows.append(item)
    if not rows or rows[0]["fix"].lower() != "today":
        stop('the first row must be the fix named "today" (nothing changed).')
    if rows[0]["one_time_cost"] or rows[0]["cost_per_year"]:
        stop('"today" must have costs of 0.')
    return rows


def score(rows, late_cost, weeks):
    today = rows[0]
    books_a_year = 52 / weeks
    for item in rows:
        saved = (today["late_orders_per_run"] - item["late_orders_per_run"]) * books_a_year
        item["late_saved_a_year"] = saved
        item["money_back_a_year"] = saved * late_cost
        item["first_year_cost"] = item["one_time_cost"] + item["cost_per_year"]
        if item is today:
            item["return_per_dollar"] = None
            item["rule"] = "baseline"
        elif item["first_year_cost"] == 0:
            item["return_per_dollar"] = None
            item["rule"] = "pass (costs nothing)" if saved > 0 else "no gain"
        else:
            ratio = item["money_back_a_year"] / item["first_year_cost"]
            item["return_per_dollar"] = ratio
            item["rule"] = "pass" if ratio >= 1.05 else "fail"
    return rows


def money(value):
    return f"-${-value:,.0f}" if value < 0 else f"${value:,.0f}"


def page(rows, late_cost, weeks):
    today = rows[0]
    body = []
    for item in rows:
        change = item["on_time_pct"] - today["on_time_pct"]
        ratio = "" if item["return_per_dollar"] is None else f"${item['return_per_dollar']:.2f}"
        cls = {"pass": "pass", "pass (costs nothing)": "pass", "fail": "fail"}.get(item["rule"], "base")
        width = max(0.0, min(100.0, item["on_time_pct"]))
        body.append(
            "<tr>"
            f"<th scope='row'>{html.escape(item['fix'])}</th>"
            f"<td><div class='bar'><span style='width:{width:.1f}%'></span></div>{item['on_time_pct']:.1f}%</td>"
            f"<td>{change:+.1f}</td>"
            f"<td>{item['late_orders_per_run']:.2f}</td>"
            f"<td>{money(item['first_year_cost'])}</td>"
            f"<td>{money(item['money_back_a_year'])}</td>"
            f"<td>{ratio}</td>"
            f"<td class='{cls}'>{item['rule']}</td>"
            "</tr>")
    return f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Fixes side by side</title>
<style>
:root{{--ink:#1f2a30;--paper:#fbf8f2;--muted:#5c676d;--line:#d9d3c7;--good:#2e7d4f;--bad:#b23b2a;--bar:#2f4858}}
@media (prefers-color-scheme: dark){{:root{{--ink:#eceae4;--paper:#1b2023;--muted:#a6adb1;--line:#3a4247;--good:#6cc08f;--bad:#f08a78;--bar:#8fb3c7}}}}
body{{margin:0;padding:24px 16px;background:var(--paper);color:var(--ink);font:16px/1.5 system-ui,sans-serif}}
main{{max-width:1240px;margin:0 auto}} h1{{font-size:1.5rem;margin:0 0 4px}} p{{color:var(--muted);margin:0 0 16px}}
.wrap{{overflow-x:auto}} table{{border-collapse:collapse;width:100%;min-width:760px}}
th,td{{text-align:left;padding:8px 10px;border-bottom:1px solid var(--line);white-space:nowrap}}
thead th{{font-size:.85rem;color:var(--muted)}} .bar{{display:inline-block;width:90px;height:8px;background:var(--line);margin-right:8px;vertical-align:middle}}
.bar span{{display:block;height:8px;background:var(--bar)}} .pass{{color:var(--good);font-weight:600}} .fail{{color:var(--bad);font-weight:600}} .base{{color:var(--muted)}}
</style></head><body><main>
<h1>Fixes side by side</h1>
<p>Each row is one twin test, 20 runs, compared to today. A late order costs {money(late_cost)}. This order book is {weeks:g} weeks of work, so a year is {52/weeks:g} order books.
The 1.05 Rule passes when each dollar spent comes back as at least $1.05 in the first year. The twin and this page do not pick a winner. You do.</p>
<div class="wrap"><table>
<thead><tr><th>Fix</th><th>On time</th><th>Change (points)</th><th>Late orders per run</th><th>First-year cost</th><th>Late cost saved a year</th><th>Back per $1</th><th>1.05 Rule</th></tr></thead>
<tbody>{''.join(body)}</tbody></table></div>
</main></body></html>
"""


def main():
    parser = argparse.ArgumentParser(description="Side-by-side page of twin fixes with the 1.05 Rule.")
    parser.add_argument("fixes")
    parser.add_argument("--late-cost", type=float, required=True, help="what one late order costs, in dollars")
    parser.add_argument("--weeks", type=float, required=True, help="how many weeks of work the order book covers")
    parser.add_argument("--out", default="fixes.html")
    args = parser.parse_args()
    if args.late_cost <= 0 or args.weeks <= 0:
        stop("--late-cost and --weeks must be above 0.")
    rows = score(read_fixes(args.fixes), args.late_cost, args.weeks)
    with open(args.out, "w") as handle:
        handle.write(page(rows, args.late_cost, args.weeks))
    print(f"{'fix':<34}{'on time':>9}{'late/run':>10}{'1st-yr cost':>13}{'saved/yr':>11}{'per $1':>8}  rule")
    for item in rows:
        ratio = "" if item["return_per_dollar"] is None else f"{item['return_per_dollar']:.2f}"
        print(f"{item['fix']:<34}{item['on_time_pct']:>8.1f}%{item['late_orders_per_run']:>10.2f}"
              f"{money(item['first_year_cost']):>13}{money(item['money_back_a_year']):>11}{ratio:>8}  {item['rule']}")
    print(f"page: {args.out}")


if __name__ == "__main__":
    main()
