#!/usr/bin/env python3
"""Turn supplier-quote JSON (ps-quote-v1) into one HTML page of follow-up email drafts, one per supplier.

Data in, drafts out. Same input and same date give the same file every time. No AI, no network.
The asks come from the same checks as build_comparison.py (it imports them), so the
comparison page and the emails always agree. Nothing is ever sent. A person reads and sends.

Usage:
    python3 build_followups.py quotes.json [more.json ...] [-o page.html] [--date YYYY-MM-DD]
        [--reply-days 2 | --reply-by YYYY-MM-DD] [--sign "Dana Ortiz" --sign "Buyer" ...] [--txt] [--json]

build_comparison.py must be in the same folder as this file.
--date is "today". It sets the expiry checks and the reply-by date. It defaults to the real date.
--reply-days is business days from today (Monday to Friday). Default 2.
--sign adds one line to the sign-off. Use it once per line. Without it, the drafts end with [YOUR NAME] spots.
--txt also writes one plain-text draft per supplier. --json also writes the asks as data.
"""
import argparse
import datetime
import json
import os
import re
import sys
from urllib.parse import quote as url_quote

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
try:
    import build_comparison as bc
except ImportError:
    print("build_followups.py needs build_comparison.py in the same folder. Attach or copy it there, then run again.",
          file=sys.stderr)
    sys.exit(1)

# ---------------------------------------------------------------- 1. THE EMAIL TEMPLATE (change wording here)
SUBJECT = "{rfq}: questions on your quote {quote_ref}"
GREETING = "Hello {first_name},"
GREETING_NO_NAME = "Hello,"
OPENING = ("Thank you for your quote for {rfq}. Before we can compare it with the others, "
           "we need a few things cleared up:")
OPENING_ONE = ("Thank you for your quote for {rfq}. Before we can compare it with the others, "
               "we need one thing cleared up:")
CLOSING = "Please reply by {reply_by}. If we misread anything, tell us and we will correct our records."
THANKS = "Thank you,"
DEFAULT_SIGNATURE = ["[YOUR NAME]", "[YOUR TITLE]", "[YOUR COMPANY]", "[YOUR PHONE]"]
REPLY_DAYS = 2

# ---------------------------------------------------------------- 2. THE ASKS (one fixed sentence per check)
# Address and contact fields are asked as one item each, so the list stays short.
GROUPS = {
    "address": (["supplier.street", "supplier.city", "supplier.state", "supplier.zip"],
                "Your full mailing address. We are missing: {fields}."),
    "contact": (["contact.name", "contact.email", "contact.phone"],
                "A contact for this quote. We are missing: {fields}."),
}
FIELD_WORDS = {
    "supplier.street": "street", "supplier.city": "city", "supplier.state": "state", "supplier.zip": "ZIP",
    "contact.name": "name", "contact.email": "email", "contact.phone": "phone",
}
ASK = {
    "supplier.name": "Your company name as it should appear on our PO.",
    "quote.number": "A quote number we can put on our PO.",
    "quote.date": "The date of this quote.",
    "quote.valid_until": "How long these prices are good for (the expiry date).",
    "terms.payment": "Your payment terms.",
    "terms.freight": "Your freight terms (for example, who pays and where it ships from).",
    "terms.freight_cost": "The freight cost to deliver to us.",
    "terms.lead_time_days": "Your lead time from PO to delivery.",
    "terms.minimum_order": "Your minimum order amount, or confirm there is none.",
}
ASK_MATH = ("Line {n}: {qty} x {price} = {right}, but the quote shows {shown}. "
            "Please confirm the correct line total.")
ASK_EXTRA = ("Line {n}, {what} ({price}), was not on our RFQ. "
             "Please tell us if it is required, or send the price without it.")
ASK_LINE_FIELDS = "Line {n}: please send the {fields}. Your quote does not show it."
ASK_EXPIRY = {
    "expired": "Your quote expired on {date}. Please confirm whether these prices still hold, or send an updated quote.",
    "today": "Your quote expires today ({date}). Please confirm you can hold these prices while we decide.",
    "soon": "Your quote expires on {date}, in {days}. Please confirm you can hold these prices while we decide.",
}
ASK_MINIMUM = ("Our lines total {lines} is below your minimum order of {minimum}. "
               "Please tell us what charge applies, or whether you can waive it.")
LINE_FIELD_WORDS = {"qty": "quantity", "uom": "unit of measure", "unit_price": "unit price"}

FOOTER = ("Built by build_followups.py from ps-quote-v1 data, using the same checks as build_comparison.py. "
          "No AI wrote these drafts. Nothing was sent. Read each one before you send it.")


# ---------------------------------------------------------------- 3. SMALL HELPERS
def join_words(words):
    if len(words) <= 2:
        return " and ".join(words)
    return ", ".join(words[:-1]) + ", and " + words[-1]


def add_business_days(day, count):
    while count > 0:
        day += datetime.timedelta(days=1)
        if day.weekday() < 5:
            count -= 1
    return day


def long_date(iso):
    day = datetime.date.fromisoformat(iso)
    return f"{day:%A}, {day:%B} {day.day}, {day.year}"


def safe_name(text):
    return re.sub(r"[^A-Za-z0-9]+", "-", text).strip("-").lower() or "supplier"


# ---------------------------------------------------------------- 4. WHAT TO ASK (the only place asks are made)
def asks_for(q, a):
    """Return the numbered asks for one quote. a is build_comparison.analyze() for the same quote."""
    asks = []
    for x in a["lines"]:
        line = x["l"]
        if x["status"] == "mismatch":
            asks.append(ASK_MATH.format(n=x["n"], qty=bc.plain_number(line["qty"]), price=bc.money(line["unit_price"]),
                                        right=bc.money(x["total"]), shown=bc.money(line["ext_price"])))
        if line["our_part"] is None:
            what = line["description"] or line["supplier_part"] or "a line with no description"
            price = "price not shown" if x["total"] is None else bc.money(x["total"])
            asks.append(ASK_EXTRA.format(n=x["n"], what=what, price=price))
        missing = [LINE_FIELD_WORDS[k] for k in bc.LINE_REQUIRED if bc.is_blank(line[k])]
        if missing:
            asks.append(ASK_LINE_FIELDS.format(n=x["n"], fields=join_words(missing)))

    missing_paths = [m["path"] for m in a["missing"]]
    done_groups = set()
    for path in missing_paths:
        group = next((g for g, (paths, _) in GROUPS.items() if path in paths), None)
        if group:
            if group in done_groups:
                continue
            done_groups.add(group)
            paths, text = GROUPS[group]
            fields = [FIELD_WORDS[p] for p in paths if p in missing_paths]
            asks.append(text.format(fields=join_words(fields)))
        else:
            asks.append(ASK[path])

    valid = q["quote"]["valid_until"]
    for flag in a["flags"]:
        if flag.startswith("Expired on "):
            asks.append(ASK_EXPIRY["expired"].format(date=valid))
        elif flag == "Expires today":
            asks.append(ASK_EXPIRY["today"].format(date=valid))
        elif flag.startswith("Expires in "):
            days = int(flag.split()[2])
            asks.append(ASK_EXPIRY["soon"].format(date=valid, days=f"{days} day{'' if days == 1 else 's'}"))
        elif flag.startswith("Lines total ") and "below the minimum" in flag:
            asks.append(ASK_MINIMUM.format(lines=bc.money(a["lines_total"]), minimum=bc.money(q["terms"]["minimum_order"])))
    return asks


# Every flag on the comparison page must turn into an ask (or be a note the buyer reads).
COVERED = ("Line ", "Freight cost not stated", "Expired on ", "Expires today", "Expires in ", "Note from the quote: ")


def uncovered_flags(a):
    """Flags this script has no ask for. If build_comparison.py learns a new check, this catches it."""
    return [f for f in a["flags"] if not f.startswith(COVERED)]


def draft_for(q, a, index, reply_by, signature):
    """Fill the fixed template for one supplier. Returns a dict with everything the page needs."""
    rfq = q["quote"]["our_rfq"] or "our RFQ"
    number = q["quote"]["number"]
    quote_ref = number if number else (f"of {q['quote']['date']}" if q["quote"]["date"] else "(no quote number)")
    contact = q["contact"]["name"]
    asks = asks_for(q, a)
    subject = SUBJECT.format(rfq=rfq, quote_ref=quote_ref)
    greeting = GREETING.format(first_name=contact.split()[0]) if contact else GREETING_NO_NAME
    opening = (OPENING_ONE if len(asks) == 1 else OPENING).format(rfq=rfq)
    body_lines = [greeting, "", opening, ""]
    body_lines += [f"{i}. {ask}" for i, ask in enumerate(asks, 1)]
    body_lines += ["", CLOSING.format(reply_by=long_date(reply_by)), "", THANKS] + signature
    return {"supplier": bc.name_of(q, index), "to": q["contact"]["email"], "contact": contact,
            "subject": subject, "asks": asks, "body": "\n".join(body_lines) if asks else "",
            "notes": q["notes"], "reply_by": reply_by}


# ---------------------------------------------------------------- 5. DRAWING THE PAGE
def mailto(d):
    to = url_quote(d["to"] or "", safe="@.+-_")
    body = d["body"].replace("\n", "\r\n")
    return f"mailto:{to}?subject={url_quote(d['subject'], safe='')}&body={url_quote(body, safe='')}"


def card(d, index):
    esc = bc.esc
    notes = ""
    if d["notes"]:
        notes = ('<details class="notes"><summary>Notes from the quote (not asked)</summary><ul>'
                 + "".join(f"<li>{esc(n)}</li>" for n in d["notes"]) + "</ul>"
                 '<p class="small-note">Read these. If one needs a question, add it to the email yourself.</p></details>')
    head = f'<h2>{esc(d["supplier"])}</h2>'
    if not d["asks"]:
        return (f'<section class="card none" id="s{index + 1}">{head}'
                '<p><span class="chip ok">Nothing to ask</span> Every required term is there and the math checks out. '
                'No email needed.</p>' + notes + "</section>")
    count = len(d["asks"])
    to_html = esc(d["to"]) if d["to"] else '<span class="warn">No email on the quote. Add one before you send.</span>'
    return (f'<section class="card" id="s{index + 1}">{head}'
            f'<p><span class="chip ask">{count} ask{"" if count == 1 else "s"}</span> '
            f'<span class="small-note">Reply by {esc(d["reply_by"])}</span></p>'
            f'<dl><dt>To</dt><dd>{to_html}</dd><dt>Subject</dt><dd class="subject">{esc(d["subject"])}</dd></dl>'
            f'<pre class="body">{esc(d["body"])}</pre>'
            '<div class="buttons">'
            f'<button type="button" class="btn" data-copy="b{index}">Copy email</button>'
            f'<button type="button" class="btn light" data-copy="s{index}">Copy subject</button>'
            f'<a class="btn light" href="{esc(mailto(d))}">Open in my email</a>'
            '<span class="copied" aria-live="polite"></span></div>'
            f'<textarea hidden id="b{index}">{esc(d["body"])}</textarea>'
            f'<textarea hidden id="s{index}">{esc(d["subject"])}</textarea>'
            + notes + "</section>")


def summary(drafts):
    rows = []
    for i, d in enumerate(drafts):
        count = len(d["asks"])
        asks = f'<span class="chip ask">{count}</span>' if count else '<span class="good">0</span>'
        to = bc.esc(d["to"]) if d["to"] else '<span class="warn">no email on quote</span>'
        rows.append(f'<tr><td><a href="#s{i + 1}">{bc.esc(d["supplier"])}</a></td><td class="num">{asks}</td><td>{to}</td></tr>')
    return ('<div class="scroll"><table><thead><tr><th>Supplier</th><th class="num">Asks</th><th>Send to</th></tr></thead>'
            "<tbody>" + "".join(rows) + "</tbody></table></div>")


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:900px;margin:0 auto;padding:20px 16px 40px}
h1{font-size:24px;margin:0 0 4px}h2{font-size:19px;margin:0 0 8px}
.sub{color:var(--slate);margin:0 0 16px}
.card{background:var(--card);border:1px solid var(--mist);border-radius:8px;padding:16px;margin:16px 0}
.card.none{border-left:5px solid var(--green)}
.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}
dl{margin:0 0 10px;display:grid;grid-template-columns:auto 1fr;gap:3px 12px}dt{color:var(--slate)}dd{margin:0}
.subject{font-weight:600}
pre.body{white-space:pre-wrap;font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;background:#fff;border:1px solid var(--mist);border-radius:6px;padding:12px;margin:0 0 12px}
.buttons{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.btn{font:inherit;font-weight:600;cursor:pointer;background:var(--blue);color:#fff;border:1px solid var(--blue);border-radius:6px;padding:7px 14px;text-decoration:none}
.btn.light{background:var(--tint);color:var(--ink);border-color:var(--mist)}
.btn:focus-visible{outline:3px solid var(--coral);outline-offset:1px}
.copied{color:var(--green);font-weight:600;font-size:13px}
.chip{display:inline-block;border-radius:10px;padding:0 8px;font-size:12px;font-weight:700;white-space:nowrap}
.ask{background:var(--coral);color:var(--ink)}.ok{background:var(--green);color:#fff}
.good{color:var(--green);font-weight:700}.warn{color:var(--red);font-weight:600}
.small-note{font-size:12px;color:var(--slate)}
.notes{margin-top:12px}.notes summary{cursor:pointer;color:var(--slate)}
.banner{background:var(--tint);border:1px solid var(--mist);border-radius:8px;padding:10px 14px}
footer{margin-top:30px;color:var(--slate);font-size:13px;border-top:1px solid var(--mist);padding-top:12px}
@media print{body{background:#fff}.buttons{display:none}.card{break-inside:avoid}}
"""

SCRIPT = """
(function(){
  function done(btn,msg){var s=btn.parentNode.querySelector('.copied');s.textContent=msg;setTimeout(function(){s.textContent='';},2500);}
  function fallback(text){var t=document.createElement('textarea');t.value=text;document.body.appendChild(t);t.select();
    var ok=false;try{ok=document.execCommand('copy');}catch(e){}document.body.removeChild(t);return ok;}
  document.querySelectorAll('[data-copy]').forEach(function(btn){
    btn.addEventListener('click',function(){
      var text=document.getElementById(btn.dataset.copy).value;
      if(navigator.clipboard&&window.isSecureContext){
        navigator.clipboard.writeText(text).then(function(){done(btn,'Copied');},function(){done(btn,fallback(text)?'Copied':'Copy failed. Select the text and copy it.');});
      }else{done(btn,fallback(text)?'Copied':'Copy failed. Select the text and copy it.');}
    });
  });
})();
"""


def build_html(drafts, rfq_label, today, reply_by):
    asked = sum(1 for d in drafts if d["asks"])
    title = f"Supplier follow-ups: {rfq_label}"
    cards = "".join(card(d, i) for i, d in enumerate(drafts))
    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>{bc.esc(title)}</title>\n<style>{CSS}</style>\n</head>\n<body>\n<main>\n"
            f"<h1>{bc.esc(title)}</h1>\n"
            f'<p class="sub">{len(drafts)} quote{"" if len(drafts) == 1 else "s"}, {asked} email{"" if asked == 1 else "s"} to send. '
            f"Drafted {bc.esc(today)}. Reply by {bc.esc(reply_by)}.</p>\n"
            '<p class="banner"><b>Drafts only.</b> Nothing has been sent. Read each email, fix anything that sounds off, '
            "and send it from your own email.</p>\n"
            f"{summary(drafts)}\n{cards}\n"
            f"<footer>{bc.esc(FOOTER)}</footer>\n</main>\n<script>{SCRIPT}</script>\n</body>\n</html>\n")


def text_file(d):
    to = d["to"] or "[NO EMAIL ON THE QUOTE. ADD ONE.]"
    return f"To: {to}\nSubject: {d['subject']}\n\n{d['body']}\n"


# ---------------------------------------------------------------- 6. COMMAND LINE
def main():
    parser = argparse.ArgumentParser(description="Build one HTML page of supplier follow-up email drafts from ps-quote-v1 JSON.")
    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: followups-<rfq>.html next to the first input.")
    parser.add_argument("--date", help="Treat this date (YYYY-MM-DD) as today.")
    parser.add_argument("--reply-days", type=int, default=REPLY_DAYS, help="Business days to reply. Default 2.")
    parser.add_argument("--reply-by", help="Reply-by date (YYYY-MM-DD). Overrides --reply-days.")
    parser.add_argument("--sign", action="append", help="One line of the sign-off. Use once per line.")
    parser.add_argument("--txt", action="store_true", help="Also write one .txt draft per supplier.")
    parser.add_argument("--json", action="store_true", help="Also write the asks as followups-<rfq>.json.")
    args = parser.parse_args()

    today = args.date or datetime.date.today().isoformat()
    if not bc.is_real_date(today):
        bc.fail(f"--date must be a date like 2026-12-31 (YYYY-MM-DD). It says {json.dumps(today)}.")
    if args.reply_by:
        if not bc.is_real_date(args.reply_by):
            bc.fail(f"--reply-by must be a date like 2026-12-31 (YYYY-MM-DD). It says {json.dumps(args.reply_by)}.")
        reply_by = args.reply_by
    else:
        if args.reply_days < 1:
            bc.fail("--reply-days must be 1 or more.")
        reply_by = add_business_days(datetime.date.fromisoformat(today), args.reply_days).isoformat()

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

    signature = args.sign or DEFAULT_SIGNATURE
    for i, q in enumerate(quotes):
        missed = uncovered_flags(bc.analyze(q, today))
        if missed:
            bc.fail(f"{bc.name_of(q, i)}: the comparison found something this script has no ask for, so no drafts were made. "
                    "Add an ask for it in section 2 of build_followups.py.\n" + "\n".join("  - " + f for f in missed))
    drafts = [draft_for(q, bc.analyze(q, today), i, reply_by, signature) for i, q in enumerate(quotes)]
    rfqs = []
    for q in quotes:
        if q["quote"]["our_rfq"] and q["quote"]["our_rfq"] not in rfqs:
            rfqs.append(q["quote"]["our_rfq"])
    rfq_label = ", ".join(rfqs) if rfqs else "no RFQ number"
    slug = re.sub(r"[^A-Za-z0-9_-]+", "-", rfqs[0]) if rfqs else "quotes"
    folder = os.path.dirname(os.path.abspath(args.inputs[0]))
    output = args.output or os.path.join(folder, f"followups-{slug}.html")
    written = [output]
    try:
        with open(output, "w", encoding="utf-8", newline="\n") as handle:
            handle.write(build_html(drafts, rfq_label, today, reply_by))
        out_dir = os.path.dirname(os.path.abspath(output))
        if args.txt:
            for d in drafts:
                if d["asks"]:
                    path = os.path.join(out_dir, f"followup-{safe_name(d['supplier'])}.txt")
                    with open(path, "w", encoding="utf-8", newline="\n") as handle:
                        handle.write(text_file(d))
                    written.append(path)
        if args.json:
            path = os.path.join(out_dir, f"followups-{slug}.json")
            record = {"format": "ps-followups-v1", "rfq": rfq_label, "drafted_on": today, "reply_by": reply_by,
                      "suppliers": [{k: d[k] for k in ("supplier", "to", "subject", "asks")} for d in drafts]}
            with open(path, "w", encoding="utf-8", newline="\n") as handle:
                handle.write(json.dumps(record, indent=2, ensure_ascii=False) + "\n")
            written.append(path)
    except OSError as problem:
        bc.fail(f"A file could not be written ({problem.strerror}).")
    counts = ", ".join(f"{d['supplier']} {len(d['asks'])}" for d in drafts)
    print(f"Wrote {', '.join(written)}")
    print(f"{len(quotes)} quotes, today = {today}, reply by {reply_by}. Asks: {counts}. Nothing was sent.")


if __name__ == "__main__":
    main()
