#!/usr/bin/env python3
"""Turn extracted supplier-quote JSON (ps-quote-v1) into one self-contained HTML comparison.

Data in, view out. Same input gives the same file every time. No AI, no network.

Usage:
    python3 build_comparison.py quotes.json [more.json ...] [-o comparison.html] [--date YYYY-MM-DD]

Each input file may hold one quote object or a list of quote objects.
--date is "today" for the expiry flags. It defaults to the real date.
"""
import argparse
import datetime
import html
import json
import os
import re
import sys
from decimal import ROUND_HALF_UP, Decimal

# ---------------------------------------------------------------- 1. THE SHAPE
SHAPE = {
    "supplier": ["name", "street", "street2", "city", "state", "zip", "phone"],
    "contact": ["name", "email", "phone"],
    "quote": ["number", "date", "valid_until", "our_rfq", "currency"],
    "terms": ["payment", "freight", "freight_cost", "lead_time_days", "minimum_order"],
}
LINE_KEYS = ["line", "our_part", "supplier_part", "description", "qty", "uom", "unit_price", "ext_price"]
NUMBER_FIELDS = ["terms.freight_cost", "terms.lead_time_days", "terms.minimum_order"]
LINE_NUMBER_FIELDS = ["line", "qty", "unit_price", "ext_price"]
LINE_TEXT_FIELDS = ["our_part", "supplier_part", "description", "uom"]
DATE_FIELDS = ["quote.date", "quote.valid_until"]

# A null in one of these counts as MISSING.
REQUIRED = [
    ("supplier.name", "Supplier name"), ("supplier.street", "Street"), ("supplier.city", "City"),
    ("supplier.state", "State"), ("supplier.zip", "ZIP"),
    ("contact.name", "Contact name"), ("contact.email", "Contact email"), ("contact.phone", "Contact phone"),
    ("quote.number", "Quote number"), ("quote.date", "Quote date"), ("quote.valid_until", "Valid until"),
    ("terms.payment", "Payment terms"), ("terms.freight", "Freight terms"),
    ("terms.freight_cost", "Freight cost"), ("terms.lead_time_days", "Lead time days"),
    ("terms.minimum_order", "Minimum order"),
]
LINE_REQUIRED = ["qty", "uom", "unit_price"]
MARGINS = [15, 20, 25, 30]
EXPIRY_WARN_DAYS = 7
FOOTER = "Built by build_comparison.py from ps-quote-v1 data. No AI was used to build this page."


# ---------------------------------------------------------------- 2. SMALL HELPERS
def is_blank(value):
    return value is None or value == ""


def is_number(value):
    return isinstance(value, (int, float)) and not isinstance(value, bool) and value == value \
        and value not in (float("inf"), float("-inf"))


def get_path(obj, path):
    for key in path.split("."):
        obj = obj.get(key) if isinstance(obj, dict) else None
    return obj


def round2(value):
    return float(Decimal(repr(float(value))).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))


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


def plain_number(value):
    """40.0 shows as 40. 51.26 shows as 51.26."""
    if isinstance(value, float) and value.is_integer():
        return str(int(value))
    return str(value)


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


def said(value):
    return " It says " + json.dumps(value, ensure_ascii=False) + "."


def is_real_date(text):
    if not isinstance(text, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", text):
        return False
    try:
        datetime.date.fromisoformat(text)
    except ValueError:
        return False
    return True


def day_number(iso):
    return datetime.date.fromisoformat(iso).toordinal()


MISSING = '<span class="chip miss">MISSING</span>'
NOT_STATED = '<span class="ns">not stated</span>'


def show(value):
    return NOT_STATED if is_blank(value) else esc(plain_number(value) if is_number(value) else value)


def show_money(value):
    return NOT_STATED if is_blank(value) else money(value)


def name_of(quote, index):
    return quote["supplier"]["name"] or f"Quote {index + 1}"


# ---------------------------------------------------------------- 3. CHECK THE INPUT
def validate(q, label):
    """Return a list of plain-English errors. Empty list means the quote is good."""
    if not isinstance(q, dict):
        return [f"{label} is not a quote object. It must start with {{ and end with }}."]
    supplier = q.get("supplier")
    supplier_name = supplier.get("name") if isinstance(supplier, dict) else None
    who = "Quote from " + (supplier_name if isinstance(supplier_name, str) and supplier_name else label)
    if q.get("format") != "ps-quote-v1":
        return [f'{who}: format must be "ps-quote-v1".' + said(q.get("format"))]
    errors = []
    for section, keys in SHAPE.items():
        if not isinstance(q.get(section), dict):
            errors.append(f'{who}: the "{section}" block is missing.')
            continue
        for key in keys:
            if key not in q[section]:
                errors.append(f'{who}: "{section}.{key}" is missing. Every key must be there. Use null if you do not know it.')
    if not isinstance(q.get("lines"), list) or not q["lines"]:
        errors.append(f'{who}: "lines" must be a list with at least one line.')
    if not isinstance(q.get("notes"), list):
        errors.append(f'{who}: "notes" must be a list (it can be empty).')
    if errors:
        return errors

    for path in NUMBER_FIELDS:
        value = get_path(q, path)
        if value is not None and not is_number(value):
            errors.append(f"{who}: {path.split('.')[1]} must be a number or null." + said(value))
    for path in DATE_FIELDS:
        value = get_path(q, path)
        if value is not None and not is_real_date(value):
            errors.append(f"{who}: {path.split('.')[1]} must be a date like 2026-12-31 (YYYY-MM-DD) or null." + said(value))
    for section, keys in SHAPE.items():
        for key in keys:
            path = f"{section}.{key}"
            value = q[section][key]
            if path in NUMBER_FIELDS or path in DATE_FIELDS:
                continue
            if value is not None and not isinstance(value, str):
                errors.append(f"{who}: {key} in {section} must be text or null." + said(value))
    for position, line in enumerate(q["lines"]):
        number = line.get("line") if isinstance(line, dict) and line.get("line") is not None else position + 1
        at = f"{who}, line {number}: "
        if not isinstance(line, dict):
            errors.append(at + "this line is not an object.")
            continue
        for key in LINE_KEYS:
            if key not in line:
                errors.append(at + f"{key} is missing. Use null if you do not know it.")
        for key in LINE_NUMBER_FIELDS:
            if key in line and line[key] is not None and not is_number(line[key]):
                errors.append(at + f"{key} must be a number." + said(line[key]))
        for key in LINE_TEXT_FIELDS:
            if key in line and line[key] is not None and not isinstance(line[key], str):
                errors.append(at + f"{key} must be text or null." + said(line[key]))
    for position, note in enumerate(q["notes"]):
        if not isinstance(note, str):
            errors.append(f"{who}: note {position + 1} must be text." + said(note))
    return errors


def load_quotes(paths):
    """Read every file. Return (quotes, errors)."""
    quotes, errors = [], []
    for path in paths:
        label = os.path.basename(path)
        try:
            with open(path, encoding="utf-8") as handle:
                data = json.load(handle)
        except FileNotFoundError:
            errors.append(f"{label}: this file was not found.")
            continue
        except OSError as problem:
            errors.append(f"{label}: this file could not be read ({problem.strerror}).")
            continue
        except UnicodeDecodeError:
            errors.append(f"{label}: this file is not plain text.")
            continue
        except json.JSONDecodeError as problem:
            errors.append(f"{label} is not valid JSON. The reader said: {problem.msg} at line {problem.lineno}, "
                          "column " + str(problem.colno) + ". Check for a missing comma, quote mark, or bracket.")
            continue
        items = data if isinstance(data, list) else [data]
        for position, item in enumerate(items):
            item_label = label + (f" item {position + 1}" if len(items) > 1 else "")
            problems = validate(item, item_label)
            if problems:
                errors.extend(problems)
            else:
                quotes.append(item)
    return quotes, errors


# ---------------------------------------------------------------- 4. THE MATH AND THE CHECKS
def analyze(q, today):
    """Every number and flag on the page comes from this one function."""
    flags = []
    incomplete = False
    lines = []
    for position, line in enumerate(q["lines"]):
        number = line["line"] if line["line"] is not None else position + 1
        known = line["qty"] is not None and line["unit_price"] is not None
        total = round2(line["qty"] * line["unit_price"]) if known else None
        status = "unknown"
        if known and line["ext_price"] is None:
            status = "computed"
        elif known and abs(line["ext_price"] - total) > 0.01:
            status = "mismatch"
            flags.append(f"Line {number} math does not match: {plain_number(line['qty'])} x "
                         f"{money(line['unit_price'])} = {money(total)}. Quote says {money(line['ext_price'])}.")
        elif known:
            status = "ok"
        if not known:
            incomplete = True
            flags.append(f"Line {number} total is unknown because qty or unit price is missing.")
        if line["our_part"] is None:
            what = line["description"] or line["supplier_part"] or "no description"
            price = "price unknown" if total is None else money(total)
            flags.append(f"Line {number} is not on our RFQ: {what} ({price})")
        missing_line = [f"line {number} {key}" for key in LINE_REQUIRED if is_blank(line[key])]
        lines.append({"n": number, "l": line, "total": total, "status": status, "missing_line": missing_line})

    lines_total = round2(sum(x["total"] or 0 for x in lines))
    freight = q["terms"]["freight_cost"]
    if freight is None:
        incomplete = True
        flags.append("Freight cost not stated")
    total = round2(lines_total + (freight or 0))

    valid = q["quote"]["valid_until"]
    if valid:
        left = day_number(valid) - day_number(today)
        if left < 0:
            flags.append(f"Expired on {valid}")
        elif left == 0:
            flags.append("Expires today")
        elif left <= EXPIRY_WARN_DAYS:
            flags.append(f"Expires in {left} day{'' if left == 1 else 's'}")

    minimum = q["terms"]["minimum_order"]
    if minimum is not None and not incomplete and lines_total < minimum:
        flags.append(f"Lines total {money(lines_total)} is below the minimum order of {money(minimum)}.")

    for note in q["notes"]:
        flags.append("Note from the quote: " + note)

    missing = [{"path": p, "label": label} for p, label in REQUIRED if is_blank(get_path(q, p))]
    missing_lines = [m for x in lines for m in x["missing_line"]]
    return {"lines": lines, "lines_total": lines_total, "freight": freight, "total": total,
            "incomplete": incomplete, "flags": flags, "missing": missing, "missing_lines": missing_lines,
            "missing_count": len(missing) + len(missing_lines)}


# ---------------------------------------------------------------- 5. DRAWING THE PAGE
def total_cell(a):
    if a["incomplete"]:
        return f'<span class="chip inc">incomplete</span> <span class="small-note">so far {money(a["total"])}</span>'
    return money(a["total"])


def definition_list(rows):
    return "<dl>" + "".join(f"<dt>{k}</dt><dd>{v}</dd>" for k, v in rows) + "</dl>"


def summary_table(A):
    done = [a["total"] for _, a in A if not a["incomplete"]]
    leads = [q["terms"]["lead_time_days"] for q, _ in A if q["terms"]["lead_time_days"] is not None]
    best_total = min(done) if len(A) > 1 and done else None
    best_lead = min(leads) if len(A) > 1 and leads else None
    rows = []
    for i, (q, a) in enumerate(A):
        lead = q["terms"]["lead_time_days"]
        best_t = " best" if not a["incomplete"] and a["total"] == best_total else ""
        best_l = " best" if lead is not None and lead == best_lead else ""
        miss = f'<span class="chip miss">{a["missing_count"]}</span>' if a["missing_count"] else '<span class="good">0</span>'
        rows.append(
            f'<tr><td><b>{esc(name_of(q, i))}</b></td><td class="num">{money(a["lines_total"])}</td>'
            f'<td class="num">{show_money(a["freight"])}</td><td class="num{best_t}">{total_cell(a)}</td>'
            f'<td class="num{best_l}">{show(lead)}</td><td>{show(q["terms"]["payment"])}</td>'
            f'<td>{show(q["quote"]["valid_until"])}</td><td class="num">{miss}</td></tr>')
    return ('<div class="scroll"><table><thead><tr><th>Supplier</th><th class="num">Lines total</th>'
            '<th class="num">Freight</th><th class="num">Total</th><th class="num">Lead time days</th>'
            '<th>Payment terms</th><th>Valid until</th><th class="num">Missing terms</th></tr></thead><tbody>'
            + "".join(rows) + '</tbody></table></div>'
            '<p class="small-note">Shaded cells show the lowest total and the shortest lead time. '
            'A person makes the call, not this page.</p>')


def by_part_table(A):
    parts = []
    for _, a in A:
        for x in a["lines"]:
            if x["l"]["our_part"] is not None and x["l"]["our_part"] not in parts:
                parts.append(x["l"]["our_part"])
    if not parts:
        return '<p class="dim">No lines match an RFQ part.</p>'
    rows = []
    for part in parts:
        units = []  # lowercase key -> first spelling
        seen = set()
        cells = []
        for _, a in A:
            mine = [x for x in a["lines"] if x["l"]["our_part"] == part]
            if not mine:
                cells.append('<td class="dim">no line</td>')
                continue
            parts_html = []
            for x in mine:
                uom = x["l"]["uom"]
                if uom is not None and uom.lower() not in seen:
                    seen.add(uom.lower())
                    units.append(uom)
                total = '<span class="chip inc">unknown</span>' if x["total"] is None else f"<b>{money(x['total'])}</b>"
                qty = "?" if is_blank(x["l"]["qty"]) else esc(plain_number(x["l"]["qty"]))
                price = "?" if is_blank(x["l"]["unit_price"]) else money(x["l"]["unit_price"])
                parts_html.append(f'{total}<div class="small-note">{qty} {esc(uom or "?")} @ {price}</div>')
            cells.append("<td>" + "".join(parts_html) + "</td>")
        flag = (f'<div class="small-note warn">Units differ ({esc(", ".join(units))}). '
                'Compare line totals, not unit prices.</div>') if len(seen) > 1 else ""
        rows.append(f"<tr><td><b>{esc(part)}</b>{flag}</td>" + "".join(cells) + "</tr>")
    heads = "".join(f"<th>{esc(name_of(q, i))}</th>" for i, (q, _) in enumerate(A))
    return (f'<div class="scroll"><table><thead><tr><th>Our part</th>{heads}</tr></thead><tbody>'
            + "".join(rows) + "</tbody></table></div>")


def missing_grid(A):
    def cell(ok):
        return '<td class="good">&#10003;</td>' if ok else f"<td>{MISSING}</td>"
    rows = []
    for path, label in REQUIRED:
        rows.append(f"<tr><td>{label}</td>" + "".join(cell(not any(m["path"] == path for m in a["missing"])) for _, a in A) + "</tr>")
    line_cells = []
    for _, a in A:
        if a["missing_lines"]:
            line_cells.append(f'<td>{MISSING} <span class="small-note">{esc(", ".join(a["missing_lines"]))}</span></td>')
        else:
            line_cells.append(cell(True))
    rows.append("<tr><td>Line qty, unit, unit price</td>" + "".join(line_cells) + "</tr>")
    heads = "".join(f"<th>{esc(name_of(q, i))}</th>" for i, (q, _) in enumerate(A))
    return (f'<div class="scroll"><table><thead><tr><th>Required field</th>{heads}</tr></thead><tbody>'
            + "".join(rows) + "</tbody></table></div>")


def flag_list(A):
    items = [f"<li><b>{esc(name_of(q, i))}:</b> {esc(f)}</li>" for i, (q, a) in enumerate(A) for f in a["flags"]]
    return '<ul class="flags">' + "".join(items) + "</ul>" if items else '<span class="good">No flags.</span>'


def margin_section(A):
    heads = "".join(f'<th class="num">{m}% margin</th>' for m in MARGINS)
    rows = []
    for i, (q, a) in enumerate(A):
        if a["incomplete"]:
            cells = '<td colspan="4"><span class="chip inc">incomplete</span> <span class="small-note">Total is not complete.</span></td>'
        else:
            cells = "".join(f'<td class="num">{money(round2(a["total"] / (1 - m / 100)))}</td>' for m in MARGINS)
        rows.append(f'<tr><td><b>{esc(name_of(q, i))}</b></td><td class="num">{total_cell(a)}</td>{cells}</tr>')
    return ('<div class="scroll"><table><thead><tr><th>Supplier</th><th class="num">Total</th>' + heads + '</tr></thead><tbody>'
            + "".join(rows) + "</tbody></table></div>"
            '<p class="small-note">Sell price = total / (1 - margin). Gross margin is the share of the sell price you keep, '
            'so a 20% margin on a $1,000 total needs a sell price of $1,250.00, not $1,200.00.</p>')


def compare_panel(A):
    return ('<section class="panel" id="p-compare"><h2>Compare</h2>'
            f"<h3>Summary</h3>{summary_table(A)}<h3>By part</h3>{by_part_table(A)}"
            f"<h3>Missing terms</h3>{missing_grid(A)}<h3>Flags</h3>{flag_list(A)}"
            f"<h3>Margin</h3>{margin_section(A)}</section>")


def supplier_panel(q, a, index):
    s, c, qt, t = q["supplier"], q["contact"], q["quote"], q["terms"]
    rows = []
    for x in a["lines"]:
        line = x["l"]
        if x["total"] is None:
            ext = NOT_STATED
        else:
            ext = money(x["total"])
            if x["status"] == "computed":
                ext += ' <span class="chip tag">computed</span>'
            if x["status"] == "mismatch":
                ext += f'<div class="small-note warn">quote says {money(line["ext_price"])}</div>'
        check = {"ok": '<span class="good">&#10003; ok</span>', "computed": '<span class="dim">computed</span>',
                 "mismatch": '<span class="chip miss">MISMATCH</span>',
                 "unknown": '<span class="chip inc">unknown</span>'}[x["status"]]
        our = '<span class="chip inc">not on our RFQ</span>' if line["our_part"] is None else esc(line["our_part"])
        rows.append(f'<tr><td>{x["n"]}</td><td>{our}</td><td>{show(line["supplier_part"])}</td>'
                    f'<td>{show(line["description"])}</td><td class="num">{show(line["qty"])}</td>'
                    f'<td>{show(line["uom"])}</td><td class="num">{show_money(line["unit_price"])}</td>'
                    f'<td class="num">{ext}</td><td>{check}</td></tr>')
    address = [v for v in (s["street"], s["street2"]) if v]
    city = ", ".join(v for v in (s["city"], " ".join(v for v in (s["state"], s["zip"]) if v)) if v)
    if city:
        address.append(city)
    address_html = "<br>".join(esc(v) for v in address) if address else NOT_STATED
    return (f'<section class="panel" id="p-s{index + 1}"><h2>{esc(name_of(q, index))}</h2>'
            '<div class="grid4">'
            f'<div class="card"><h3>Supplier</h3>{definition_list([("Name", show(s["name"])), ("Address", address_html), ("Phone", show(s["phone"]))])}</div>'
            f'<div class="card"><h3>Contact</h3>{definition_list([("Name", show(c["name"])), ("Email", show(c["email"])), ("Phone", show(c["phone"]))])}</div>'
            f'<div class="card"><h3>Quote</h3>{definition_list([("Number", show(qt["number"])), ("Date", show(qt["date"])), ("Valid until", show(qt["valid_until"])), ("Our RFQ", show(qt["our_rfq"])), ("Currency", show(qt["currency"]))])}</div>'
            f'<div class="card"><h3>Terms</h3>{definition_list([("Payment", show(t["payment"])), ("Freight", show(t["freight"])), ("Freight cost", show_money(t["freight_cost"])), ("Lead time (days)", show(t["lead_time_days"])), ("Minimum order", show_money(t["minimum_order"]))])}</div>'
            '</div><h3>Lines</h3><div class="scroll"><table><thead><tr><th>Line</th><th>Our part</th><th>Supplier part</th>'
            '<th>Description</th><th class="num">Qty</th><th>UOM</th><th class="num">Unit price</th>'
            '<th class="num">Ext price</th><th>Check</th></tr></thead><tbody>' + "".join(rows) +
            f'</tbody><tfoot><tr><td colspan="7">Lines total</td><td class="num">{money(a["lines_total"])}</td><td></td></tr>'
            f'<tr><td colspan="7">Freight</td><td class="num">{show_money(a["freight"])}</td><td></td></tr>'
            f'<tr><td colspan="7">Total</td><td class="num">{total_cell(a)}</td><td></td></tr></tfoot></table></div></section>')


CSS = """
:root{--paper:#F4F6FA;--ink:#18202E;--blue:#2456C4;--coral:#F47A5E;--tint:#E6ECF6;--mist:#C7D4E7;--slate:#546071;--red:#B02A1E;--green:#2E7D4F;--card:#FBFCFE}
*{box-sizing:border-box}
body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
main{max-width:1200px;margin:0 auto;padding:20px 16px 40px}
h1{font-size:24px;margin:0 0 4px}h2{font-size:19px;margin:0 0 12px}h3{font-size:15px;margin:22px 0 8px;color:var(--blue)}
.sub{color:var(--slate);margin:0 0 16px}
.card{background:var(--card);border:1px solid var(--mist);border-radius:8px;padding:14px;margin-bottom:14px}
.tabs{display:none;gap:4px;flex-wrap:wrap;border-bottom:2px solid var(--mist);margin:18px 0 14px}
.js .tabs{display:flex}
.tab{font:inherit;cursor:pointer;background:var(--tint);color:var(--ink);border:1px solid var(--mist);border-bottom:none;border-radius:6px 6px 0 0;padding:7px 14px}
.tab.on{background:var(--blue);color:#fff;border-color:var(--blue)}
.tab:focus-visible{outline:3px solid var(--coral);outline-offset:1px}
.panel{display:block;margin-bottom:28px}
.js .panel{display:none}.js .panel.on{display:block}
.scroll{overflow-x:auto}
table{border-collapse:collapse;width:100%;background:var(--card)}
th,td{border:1px solid var(--mist);padding:6px 9px;text-align:left;vertical-align:top}
th{background:var(--tint);font-weight:600;font-size:13px}
td.num,th.num{text-align:right;font-variant-numeric:tabular-nums}
td.best{background:#DCE6FA;font-weight:600}
tfoot td{font-weight:600;background:var(--tint)}
.chip{display:inline-block;border-radius:10px;padding:0 8px;font-size:12px;font-weight:700;white-space:nowrap}
.miss{background:var(--red);color:#fff}.inc{background:var(--coral);color:var(--ink)}.tag{background:var(--mist);color:var(--ink)}
.ns{color:var(--red);font-weight:600}
.dim{color:var(--slate)}.good{color:var(--green);font-weight:700}.warn{color:var(--red)}
.small-note{font-size:12px;color:var(--slate)}
.grid4{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:12px}
dl{margin:0;display:grid;grid-template-columns:auto 1fr;gap:3px 12px}dt{color:var(--slate)}dd{margin:0}
ul.flags{margin:0;padding-left:20px}ul.flags li{margin:3px 0}
footer{margin-top:30px;color:var(--slate);font-size:13px;border-top:1px solid var(--mist);padding-top:12px}
@media print{body{background:#fff}.tabs{display:none!important}.panel{display:block!important;break-after:page}.panel:last-of-type{break-after:auto}.card{break-inside:avoid}main{padding:0}}
"""

# Tabs only. With JS off, every panel shows.
SCRIPT = """
(function(){
  document.documentElement.classList.add("js");
  var tabs=document.querySelectorAll(".tab"),panels=document.querySelectorAll(".panel");
  function show(id){
    tabs.forEach(function(t){t.classList.toggle("on",t.dataset.tab===id);t.setAttribute("aria-selected",t.dataset.tab===id);});
    panels.forEach(function(p){p.classList.toggle("on",p.id==="p-"+id);});
  }
  tabs.forEach(function(t){t.addEventListener("click",function(){show(t.dataset.tab);});});
  show("compare");
})();
"""


def json_for_script(quotes):
    text = json.dumps(quotes, indent=2, ensure_ascii=False)
    return text.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") \
        .replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")


def build_html(quotes, today):
    A = [(q, analyze(q, today)) for q in quotes]
    rfqs = []
    for q in quotes:
        rfq = q["quote"]["our_rfq"]
        if rfq and rfq not in rfqs:
            rfqs.append(rfq)
    rfq_label = ", ".join(rfqs) if rfqs else "no RFQ number"
    title = f"Quote comparison: {rfq_label}"
    tabs = '<button class="tab" data-tab="compare" role="tab">Compare</button>' + "".join(
        f'<button class="tab" data-tab="s{i + 1}" role="tab">{esc(name_of(q, i))}</button>' for i, (q, _) in enumerate(A))
    panels = compare_panel(A) + "".join(supplier_panel(q, a, i) for i, (q, a) in enumerate(A))
    return ("<!doctype html>\n"
            '<html lang="en">\n<head>\n<meta charset="utf-8">\n'
            '<meta name="viewport" content="width=device-width, initial-scale=1">\n'
            f"<title>{esc(title)}</title>\n<style>{CSS}</style>\n</head>\n<body>\n<main>\n"
            f"<h1>{esc(title)}</h1>\n"
            f'<p class="sub">{len(A)} quote{"" if len(A) == 1 else "s"}. Expiry flags use {esc(today)} as today.</p>\n'
            f'<div class="tabs" role="tablist">{tabs}</div>\n{panels}\n'
            f"<footer>{esc(FOOTER)}</footer>\n</main>\n"
            f'<script type="application/json" id="quote-data">{json_for_script(quotes)}</script>\n'
            f"<script>{SCRIPT}</script>\n</body>\n</html>\n"), rfqs


# ---------------------------------------------------------------- 6. COMMAND LINE
def fail(message):
    print(message, file=sys.stderr)
    sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description="Build one HTML comparison from ps-quote-v1 JSON files.")
    parser.add_argument("inputs", nargs="+", help="JSON file(s). Each holds one quote or a list of quotes.")
    parser.add_argument("-o", "--output", help="Output HTML path. Default: quote-comparison-<rfq>.html next to the first input.")
    parser.add_argument("--date", help="Treat this date (YYYY-MM-DD) as today for expiry flags.")
    args = parser.parse_args()

    today = args.date or datetime.date.today().isoformat()
    if not is_real_date(today):
        fail(f"--date must be a date like 2026-12-31 (YYYY-MM-DD). It says {json.dumps(today)}.")

    quotes, errors = load_quotes(args.inputs)
    if errors:
        fail("These quotes were not used. Nothing was built. Fix the data and run again.\n"
             + "\n".join("  - " + e for e in errors))
    if not quotes:
        fail("No quotes were found in the input files.")

    page, rfqs = build_html(quotes, today)
    output = args.output
    if not output:
        slug = re.sub(r"[^A-Za-z0-9_-]+", "-", rfqs[0]) if rfqs else "quotes"
        output = os.path.join(os.path.dirname(os.path.abspath(args.inputs[0])), f"quote-comparison-{slug}.html")
    try:
        with open(output, "w", encoding="utf-8", newline="\n") as handle:
            handle.write(page)
    except OSError as problem:
        fail(f"The output file {output} could not be written ({problem.strerror}).")
    print(f"Wrote {output} ({len(quotes)} quotes, today = {today}).")


if __name__ == "__main__":
    main()
