#!/usr/bin/env python3
"""Generate the HARD set for the Pondero Labs document-extraction test (set B).

Set A (gen.py) turned out to be too easy: four of six models were perfect. Set B is modelled on
three kinds of invoice that accounts payable teams find hard, with invented vendors:

  rental     18  equipment rental invoices in the layout the big US rental houses use: every line
                 prints the Min / Day / Week / 4-Week RATES beside the billed AMOUNT, with make /
                 model / serial sub-rows, meter hours, protection plan, environmental charge,
                 delivery, pickup, fuel and tax.
  paint      12  paint-supplier invoices: product numbers, colour codes and tint formulas inside
                 the line items, list price beside net price, returns, per-container stewardship fees.
  screening  10  workforce drug-testing invoices: a summary by service code plus pages of
                 per-donor detail rows grouped by site (donor IDs only, no names).

The answer key comes from the same records that render the pages, so it is exact by construction.
Usage:  venv/bin/python gen2.py   -> docs-b/*.pdf, answer-key-b.json, manifest-b.csv
"""
import csv, datetime as dt, glob, json, os, random
from decimal import Decimal, ROUND_HALF_UP
import fitz
import gen as A   # reuse the renderer and the scan degrader

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, 'docs-b')
rng = random.Random(20261202)
D2 = Decimal('0.01')
def q(x): return Decimal(str(x)).quantize(D2, rounding=ROUND_HALF_UP)
def m(x): return f'{q(x):,.2f}'
def us(d): return d.strftime('%m/%d/%y')
e = A.e
BUYER = dict(name='Halden Row Industrial Services LLC', addr=['4400 Shipyard Parkway', 'Pasadena, TX 77506'], acct=None)

CSS = A.CSS + """
.mono, .mono td, .mono th { font-family: 'Liberation Mono', 'DejaVu Sans Mono', monospace; font-size: 8.2pt; }
.tight td, .tight th { padding: 2px 4px; } .sub td { color: #333; font-size: 7.6pt; padding-top: 0; border-bottom: none; }
.hdr td { vertical-align: top; font-size: 8.6pt; padding: 1px 6px 1px 0; } .lbl { color: #555; }
.rule { border-top: 1.2px solid #111; } .small { font-size: 7.4pt; color: #444; line-height: 1.25; }
.sect { background: #e9edf1; font-weight: 700; font-size: 8.2pt; padding: 3px 5px; margin-top: 8px; letter-spacing: .04em; }
.nob td { border-bottom: none !important; }
.items td:first-child { white-space: nowrap; }
"""

# ============================================================== RENTAL
RENTERS = [
    dict(name='Ironbridge Rentals Inc.', brand='IRONBRIDGE RENTALS', layout='h', addr='Branch 418 · 9120 Wallisville Rd, Houston, TX 77029 · 713-555-0144', prefix='', ra='R.A. No.'),
    dict(name='Tallgrass Equipment Rental LLC', brand='Tallgrass Equipment Rental', layout='u', addr='Location T07 · 2255 Industrial Blvd, Baton Rouge, LA 70805 · 225-555-0190', prefix='', ra='Rental Agreement #'),
    dict(name='Cascade Fleet Rentals Corp.', brand='CASCADE FLEET', layout='s', addr='PC 0612 · 610 Port Access Rd, Lake Charles, LA 70601 · 337-555-0121', prefix='', ra='Contract #'),
]
FLEET = [  # description, make, model, day, week, 4-week
    ("BOOM 60' ARTICULATING 4WD DSL", 'JLG', '600AJ', 495, 1385, 3290), ("SCISSOR LIFT 26' ELECTRIC", 'GENIE', 'GS-2646', 165, 395, 795),
    ("FORKLIFT REACH 10000# 44'", 'SKYTRAK', '10054', 610, 1750, 4380), ('LIGHT TOWER 4000W DSL TOWABLE', 'WACKER', 'LTN6', 110, 300, 705),
    ('COMPRESSOR 185CFM DSL TOWABLE', 'SULLAIR', '185DPQ', 150, 420, 980), ('EXCAVATOR MINI 8000-9000#', 'KUBOTA', 'KX040-4', 385, 1190, 2950),
    ('SKID STEER TRACK 2200#', 'BOBCAT', 'T66', 365, 1095, 2695), ('GENERATOR 56KW DSL TOWABLE', 'MULTIQUIP', 'DCA70', 290, 795, 1950),
    ('WELDER 400A DSL TOWABLE', 'LINCOLN', 'VANTAGE 400', 120, 340, 790), ('TRUCK PICKUP 3/4T CREW 4WD', 'FORD', 'F250', 125, 560, 1650),
    ('CRANE CARRY DECK 9T', 'BRODERSON', 'IC-80', 720, 2150, 5400), ('HEATER 400K BTU INDIRECT DSL', 'FROST FIGHTER', 'IDF400', 135, 390, 940),
    ('PUMP TRASH 4IN DSL TOWABLE', 'GORMAN-RUPP', '14C2', 140, 395, 985), ("TELEHANDLER 6000# 42'", 'JCB', '507-42', 480, 1390, 3350),
    ("BOOM 45' TELESCOPIC 4WD DSL", 'GENIE', 'S-45', 410, 1120, 2640), ('AIR SCRUBBER 2000CFM HEPA', 'ABATEMENT TECH', 'PAS2400', 95, 260, 610),
]
SALES = [('DIESEL FUEL (GAL)', 6.89), ('PROPANE CYLINDER 33# REFILL', 34.50), ('CUTOFF WHEEL 14IN', 18.75), ('HARNESS LANYARD KIT', 96.00), ('HYDRAULIC HOSE REPAIR', 212.40), ('CLEANING CHARGE', 85.00)]

def roll(days, day, week, four):
    """Rate roll: bill the cheapest of days / weeks / 4-week periods, as rental houses do."""
    n4, rem = divmod(days, 28); w, d = divmod(rem, 7)
    dpart = min(q(d * day), q(week))
    wpart = min(q(w * week) + dpart, q(four))
    return q(n4 * four) + wpart, (n4, w, d)

def make_rental(i, tier):
    v = RENTERS[i % 3]
    kind = rng.choices(['cycle_bill', 'final_return', 'credit'], [0.5, 0.38, 0.12])[0]
    n = rng.choice([3, 4, 5, 6, 8, 11, 14, 19, 24]) if kind != 'credit' else rng.choice([1, 2, 3])
    frm = dt.date(2026, rng.randint(6, 10), rng.randint(1, 26))
    thru = frm + dt.timedelta(days=28 if kind == 'cycle_bill' else rng.randint(3, 25))
    lines, used = [], set()
    for k in range(n):
        desc, make, model, day, week, four = rng.choice(FLEET)
        adj = Decimal(str(rng.choice([1, 1, 0.92, 0.88, 1.06])))          # contract pricing differs from book
        day, week, four = q(day * adj), q(week * adj), q(four * adj)
        while True:
            eq = f"{rng.choice(['8003', '8011', '1042', '9076'])}{rng.randint(10000, 99999)}"
            if eq not in used: used.add(eq); break
        out = frm if (kind == 'cycle_bill' and rng.random() < 0.7) else frm + dt.timedelta(days=rng.randint(0, 9))
        if out >= thru: out = frm
        inn = thru if rng.random() < 0.75 else out + dt.timedelta(days=rng.randint(1, max(1, (thru - out).days)))
        days = max(1, (inn - out).days)
        qty = rng.choice([1, 1, 1, 1, 2, 4]) if day < 200 else 1
        unit, basis = roll(days, day, week, four)
        amount = q(unit * qty)
        hrs_out = rng.randint(120, 4800); used_hrs = rng.randint(4, 9) * days if days < 28 else rng.randint(90, 175)
        lines.append(dict(equipment_number=eq, description=desc, make=make, model=model, serial=''.join(rng.choice('0123456789ABCDEFGHJKLMNPRSTUVWXYZ') for _ in range(rng.choice([11, 13, 17]))),
                          quantity=qty, day_rate=day, week_rate=week, four_week_rate=four, amount=amount, out=out, inn=inn, days=days, basis=basis, hrs_out=hrs_out, hrs_in=hrs_out + used_hrs))
    sign = -1 if kind == 'credit' else 1
    for ln in lines: ln['amount'] = sign * ln['amount']
    rental = sum(ln['amount'] for ln in lines)
    rpp_on = rng.random() < 0.72
    rpp = q(rental * Decimal('0.15')) if rpp_on else Decimal('0')
    env = sign * min(q(abs(rental) * Decimal('0.021')), Decimal('99.00'))
    delivery = q(rng.choice([0, 95, 145, 185, 240, 285])) if kind == 'cycle_bill' and rng.random() < 0.55 else Decimal('0')
    pickup = q(rng.choice([95, 145, 185, 240, 285])) if kind == 'final_return' else Decimal('0')
    tss = max(q((delivery + pickup) * Decimal('0.12')), Decimal('12.00')) if (delivery + pickup) else Decimal('0')
    sales = []
    if kind != 'credit' and rng.random() < 0.6:
        for desc, price in rng.sample(SALES, rng.randint(1, 3)):
            sq = rng.choice([1, 2, 6, 18, 42]) if 'FUEL' in desc else rng.choice([1, 1, 2, 4])
            sales.append((desc, sq, q(price), q(sq * price)))
    sales_total = sum(s[3] for s in sales)
    exempt = rng.random() < 0.2
    rate = Decimal('0') if exempt else Decimal(rng.choice(['0.0825', '0.0945', '0.1045']))
    taxable = rental + rpp + env + delivery + pickup + tss + sales_total
    tax = q(taxable * rate)
    total = taxable + tax
    number = f"{rng.randint(31000000, 36999999)}-{rng.randint(1, 14):03d}"
    ra = f"{rng.randint(31000000, 36999999)}"
    truth = dict(vendor_name=v['name'], invoice_number=number, invoice_date=(thru + dt.timedelta(days=1)).isoformat(), rental_agreement_number=ra,
                 po_number=f"{rng.randint(4500100000, 4500999999)}", job_number=(f"J-{rng.randint(22000, 29999)}" if rng.random() < 0.7 else None),
                 billed_from=frm.isoformat(), billed_through=thru.isoformat(), invoice_type=kind,
                 rental_subtotal=float(rental), rental_protection_plan=float(rpp), environmental_charge=float(env),
                 delivery_charge=float(delivery), pickup_charge=float(pickup), sales_items_total=float(sales_total), tax_total=float(tax), total=float(total),
                 lines=[dict(equipment_number=l['equipment_number'], quantity=l['quantity'], day_rate=float(l['day_rate']), week_rate=float(l['week_rate']),
                             four_week_rate=float(l['four_week_rate']), amount=float(l['amount'])) for l in lines])
    return dict(id=f'rent-{i:02d}', family='rental', tier=tier, truth=truth, v=v,
                r=dict(lines=lines, kind=kind, frm=frm, thru=thru, rental=rental, rpp=rpp, rpp_on=rpp_on, env=env, delivery=delivery, pickup=pickup, tss=tss, sales=sales,
                       sales_total=sales_total, rate=rate, exempt=exempt, tax=tax, total=total, number=number, ra=ra, acct=f"{rng.randint(1200000, 1899999)}"))

def rental_html(rec):
    v, r, t = rec['v'], rec['r'], rec['truth']
    title = {'cycle_bill': 'INVOICE - 4 WEEK CYCLE BILL', 'final_return': 'INVOICE - RENTAL RETURN', 'credit': 'CREDIT MEMO'}[r['kind']]
    inv_date = dt.date.fromisoformat(t['invoice_date'])
    head = f"""<table><tr><td style='width:56%;vertical-align:top'><div class='brand'>{e(v['brand'])}</div><div class='small'>{e(v['name'])}<br>{e(v['addr'])}</div></td>
<td style='vertical-align:top;text-align:right'><b style='font-size:12pt'>{title}</b><div class='mono'>Invoice No. <b>{e(r['number'])}</b><br>Invoice Date {us(inv_date)}<br>{e(v['ra'])} {e(r['ra'])}<br>Page 1</div></td></tr></table>
<table class='hdr mono' style='margin-top:8px;border-top:1.2px solid #111;border-bottom:1.2px solid #111'><tr>
<td style='width:38%'><span class='lbl'>BILL TO</span><br><b>{e(BUYER['name'])}</b><br>{'<br>'.join(e(a) for a in BUYER['addr'])}<br><span class='lbl'>CUSTOMER #</span> {e(r['acct'])}</td>
<td style='width:31%'><span class='lbl'>JOB SITE</span><br>UNIT 4 TURNAROUND<br>1800 REFINERY RD GATE 6<br>DEER PARK, TX 77536<br><span class='lbl'>ORDERED BY</span> M. DELACROIX</td>
<td><span class='lbl'>PO# / JOB#</span> {e(t['po_number'])}{' / ' + e(t['job_number']) if t['job_number'] else ''}<br><span class='lbl'>BILLED FROM</span> {us(r['frm'])} 07:00<br><span class='lbl'>BILLED THRU</span> {us(r['thru'])} 07:00<br><span class='lbl'>SALESPERSON</span> 0{rng.randint(1000, 9999)}<br><span class='lbl'>TERMS</span> NET 30</td></tr></table>"""
    lay = v['layout']
    if lay == 'h':
        th = "<tr><th>Qty</th><th>Equipment #</th><th class='r'>Hrs/Min</th><th class='r'>Hour</th><th class='r'>Day</th><th class='r'>Week</th><th class='r'>4 Week</th><th class='r'>Amount</th></tr>"
    elif lay == 'u':
        th = "<tr><th>Qty</th><th>Equipment</th><th>Description</th><th class='r'>Minimum</th><th class='r'>Day</th><th class='r'>Week</th><th class='r'>4 Week</th><th class='r'>Amount</th></tr>"
    else:
        th = "<tr><th>Equip #</th><th>Description</th><th>Out - In</th><th class='r'>Qty</th><th class='r'>Daily</th><th class='r'>Weekly</th><th class='r'>4Wk</th><th class='r'>Ext Amount</th></tr>"
    def row(l):
        mn = m(q(l['day_rate'] * Decimal('0.75'))); hr = m(q(l['four_week_rate'] / 160))
        n4, w, d = l['basis']; basis = ' '.join(x for x in [f'{n4} 4WK' if n4 else '', f'{w} WK' if w else '', f'{d} DAY' if d else ''] if x)
        if lay == 'h':
            return (f"<tr><td>{l['quantity']}</td><td><b>{e(l['description'])}</b></td><td class='r'>8/{mn}</td><td class='r'>{hr}</td><td class='r'>{m(l['day_rate'])}</td><td class='r'>{m(l['week_rate'])}</td><td class='r'>{m(l['four_week_rate'])}</td><td class='r'><b>{m(l['amount'])}</b></td></tr>"
                    f"<tr class='sub'><td></td><td colspan='7'>{e(l['equipment_number'])} Make: {e(l['make'])} Model: {e(l['model'])} Ser #: {e(l['serial'])} &nbsp; HR OUT: {l['hrs_out']:,}.0 HR IN: {l['hrs_in']:,}.0 TOTAL: {l['hrs_in']-l['hrs_out']}.0 &nbsp; OUT {us(l['out'])} IN {us(l['inn'])}</td></tr>")
        if lay == 'u':
            return (f"<tr><td>{l['quantity']}</td><td>{e(l['equipment_number'])}</td><td><b>{e(l['description'])}</b></td><td class='r'>{mn}</td><td class='r'>{m(l['day_rate'])}</td><td class='r'>{m(l['week_rate'])}</td><td class='r'>{m(l['four_week_rate'])}</td><td class='r'><b>{m(l['amount'])}</b></td></tr>"
                    f"<tr class='sub'><td></td><td colspan='7'>Make: {e(l['make'])} &nbsp; Model: {e(l['model'])} &nbsp; Serial: {e(l['serial'])} &nbsp; Meter out: {l['hrs_out']}.00 &nbsp; Meter in: {l['hrs_in']}.00 &nbsp; Rental period {us(l['out'])} thru {us(l['inn'])} ({l['days']} days, billed {basis})</td></tr>")
        return (f"<tr><td>{e(l['equipment_number'])}</td><td><b>{e(l['description'])}</b><br><span class='small'>{e(l['make'])} {e(l['model'])} S/N {e(l['serial'])} · HRS {l['hrs_out']}/{l['hrs_in']}</span></td><td>{us(l['out'])} - {us(l['inn'])}</td><td class='r'>{l['quantity']}</td>"
                f"<td class='r'>{m(l['day_rate'])}</td><td class='r'>{m(l['week_rate'])}</td><td class='r'>{m(l['four_week_rate'])}</td><td class='r'><b>{m(l['amount'])}</b></td></tr>")
    per_page = 9 if lay != 's' else 10
    chunks = [r['lines'][k:k + per_page] for k in range(0, len(r['lines']), per_page)]
    body = ''
    for ci, ch in enumerate(chunks):
        if ci: body += f"<div class='pb'></div><div class='mono'>{e(v['brand'])} · Invoice No. {e(r['number'])} · Page {ci+1} · RENTAL ITEMS (continued)</div>"
        body += f"<div class='sect'>RENTAL ITEMS</div><table class='items mono tight'>{th}{''.join(row(l) for l in ch)}</table>"
        if ci < len(chunks) - 1: body += "<div class='mono' style='text-align:right'>CONTINUED ON NEXT PAGE</div>"
    tot = [('Rental Subtotal', r['rental'])]
    sales_html = ''
    if r['sales']:
        sales_html = "<div class='sect'>SALES / MISCELLANEOUS ITEMS</div><table class='items mono tight'><tr><th>Qty</th><th>Item</th><th class='r'>Price</th><th class='r'>Unit</th><th class='r'>Extended</th></tr>" + \
                     ''.join(f"<tr><td>{s[1]}</td><td>{e(s[0])}</td><td class='r'>{m(s[2])}</td><td class='r'>EA</td><td class='r'>{m(s[3])}</td></tr>" for s in r['sales']) + '</table>'
        tot.append(('Sales / Misc Subtotal', r['sales_total']))
    tot.append(('Rental Protection Plan 15%' if r['rpp_on'] else 'Rental Protection Plan - DECLINED (COI ON FILE)', r['rpp']))
    tot.append(('Environmental Service Charge', r['env']))
    if r['delivery']: tot.append(('Delivery Charge', r['delivery']))
    if r['pickup']: tot.append(('Pickup Charge', r['pickup']))
    if r['tss']: tot.append(('Transportation Surcharge 12%', r['tss']))
    tot.append((f"Sales Tax {r['rate']*100:.2f}%" if not r['exempt'] else 'Sales Tax - EXEMPT (CERT ON FILE)', r['tax']))
    tot_html = ''.join(f"<tr><td>{e(a)}</td><td class='r'>{m(b)}</td></tr>" for a, b in tot) + f"<tr class='grand'><td>{'CREDIT TOTAL' if r['kind']=='credit' else 'INVOICE TOTAL'} USD</td><td class='r'>{m(r['total'])}</td></tr>"
    notes = "<div class='small' style='margin-top:10px'>Rates shown are for one-shift use: 8 hours per day, 40 hours per week, 160 hours per 4 weeks. Use beyond one shift is billed at the hourly rate shown. " \
            "The Rental Protection Plan is not insurance. Fuel is charged when equipment is returned below the fuel level at delivery. " + \
            (f"NEXT BILLING DATE {us(r['thru'] + dt.timedelta(days=28))}. " if r['kind'] == 'cycle_bill' else '') + "Remit to: Lockbox 771204, Dallas, TX 75377.</div>"
    return f"<html><head><meta charset='utf-8'><style>{CSS}</style></head><body>{head}{body}{sales_html}<table class='totals mono' style='width:52%;margin-left:48%'>{tot_html}</table>{notes}</body></html>"

# ============================================================== PAINT
PAINTERS = [dict(name='Harlan-Whitlock Paint Company', brand='HARLAN-WHITLOCK PAINTS', cc='HW', store='Store 7214 · 3890 Spencer Hwy, Pasadena, TX 77504'),
            dict(name='Corbel & Lathe Coatings Inc.', brand='Corbel & Lathe Coatings', cc='CL', store='Branch 0338 · 1175 Airline Dr, Metairie, LA 70001')]
PRODUCTS = [('PM200 0VOC INT LATEX EG-SHEL', 'B20W', [('1GAL', 46.89, 31.42), ('5GAL', 221.45, 148.37)]), ('DURACRAFT ACRYLIC INT FLAT', 'A86W', [('1GAL', 38.99, 24.18), ('5GAL', 182.95, 113.65)]),
            ('PRO INDUSTRIAL DTM ACRYLIC GLOSS', 'B66W', [('1GAL', 84.29, 57.32), ('5GAL', 401.95, 273.33)]), ('MACROPOXY 646 FC EPOXY PT A', 'B58W', [('1GAL', 96.79, 68.72), ('5GAL', 462.95, 328.69)]),
            ('ACROLON 218 HS POLYURETHANE', 'B65W', [('1GAL', 118.49, 86.5), ('5GAL', 571.95, 417.52)]), ('EXT ACRYLIC LATEX SATIN', 'A82W', [('1GAL', 61.99, 40.29), ('5GAL', 296.95, 193.02)]),
            ('KEM BOND HS UNIVERSAL PRIMER', 'B50W', [('1GAL', 72.19, 49.81), ('5GAL', 344.95, 238.02)])]
COLORS = [('7029', 'AGREEABLE GREIGE'), ('7005', 'PURE WHITE'), ('6258', 'TRICORN BLACK'), ('4086', 'SAFETY YELLOW'), ('4081', 'SAFETY RED'), ('7064', 'PASSIVE GRAY'), ('6244', 'NAVAL'), ('7674', 'PEPPERCORN'), ('4031', 'PIPELINE GREEN'), ('2847', 'ROYCROFT BOTTLE GREEN')]
TINTS = ['B1-BLACK', 'R2-MAROON', 'Y3-DEEP GOLD', 'W1-WHITE', 'N1-RAW UMBER', 'G2-NEW GREEN', 'L1-BLUE', 'R3-MAGENTA']
SUNDRY = [('PURDY WHITE DOVE ROLLER 9IN 3/8', '153-4587', 'EA', 9.49, 6.83), ('FROGTAPE MULTI-SURFACE 1.41IN', '204-1163', 'RL', 8.99, 6.2), ('WOOSTER SHERLOCK FRAME 9IN', '158-9925', 'EA', 12.29, 8.9),
          ('TRIMACO DROP CLOTH 9X12', '112-6504', 'EA', 24.99, 17.6), ('XYLENE 1GAL', '154-3211', 'GL', 28.49, 21.05), ('TIP 517 AIRLESS RAC X', '209-7740', 'EA', 44.99, 33.75)]
FEE = {'1GAL': Decimal('0.99'), '5GAL': Decimal('1.99')}

def make_paint(i, tier):
    v = PAINTERS[i % 2]
    n = rng.choice([3, 4, 5, 7, 9, 12])
    lines, seen = [], set()
    for k in range(n):
        if rng.random() < 0.7:
            name, base, sizes = rng.choice(PRODUCTS); size, lst, net = rng.choice(sizes)
            code, cname = rng.choice(COLORS)
            sku = f"{rng.randint(6400, 6699)}-{rng.randint(10000, 99999)}"
            ckey = f"{v['cc']} {code}"
            if (sku, ckey) in seen: continue
            seen.add((sku, ckey))
            qty = rng.choice([1, 2, 3, 4, 6, 10]); ret = rng.random() < 0.1
            if ret: qty = -rng.choice([1, 2])
            tint = '  '.join(f"{t} {rng.choice(['-', 2, 4, 6])} {rng.randint(1, 31)} {rng.choice(['-', 1])} {rng.choice(['-', 1])}" for t in rng.sample(TINTS, rng.randint(2, 3)))
            lines.append(dict(sales_number=sku, description=f'{name} {base}{rng.randint(1000, 9999)}', quantity=qty, unit=size, color_code=ckey, color_name=cname, tint=tint, list=q(lst), unit_price=q(net), amount=q(qty * net), paint=True, ret=ret))
        else:
            name, sku, uom, lst, net = rng.choice(SUNDRY)
            if (sku, None) in seen: continue
            seen.add((sku, None)); qty = rng.choice([1, 2, 4, 6, 12])
            lines.append(dict(sales_number=sku, description=name, quantity=qty, unit=uom, color_code=None, color_name=None, tint=None, list=q(lst), unit_price=q(net), amount=q(qty * net), paint=False, ret=False))
    subtotal = sum(l['amount'] for l in lines)
    fee = sum(FEE[l['unit']] * l['quantity'] for l in lines if l['paint'])
    rate = Decimal(rng.choice(['0.0825', '0.0945', '0']))
    tax = q((subtotal + fee) * rate); total = subtotal + fee + tax
    d = dt.date(2026, rng.randint(6, 11), rng.randint(1, 27))
    truth = dict(vendor_name=v['name'], invoice_number=f"{rng.randint(1000, 9999)}-{rng.randint(1, 9)}", invoice_date=d.isoformat(), account_number=f"{rng.randint(2000, 9999)}-{rng.randint(1000, 9999)}-{rng.randint(1, 9)}",
                 po_number=f"{rng.randint(4500100000, 4500999999)}", subtotal=float(subtotal), stewardship_fee_total=float(fee), tax_total=float(tax), total=float(total),
                 lines=[dict(sales_number=l['sales_number'], color_code=l['color_code'], quantity=l['quantity'], unit=l['unit'], unit_price=float(l['unit_price']), amount=float(l['amount'])) for l in lines])
    return dict(id=f'paint-{i:02d}', family='paint', tier=tier, truth=truth, v=v, r=dict(lines=lines, subtotal=subtotal, fee=fee, rate=rate, tax=tax, total=total, d=d))

def paint_html(rec):
    v, r, t = rec['v'], rec['r'], rec['truth']
    head = f"""<table><tr><td style='width:58%;vertical-align:top'><div class='brand'>{e(v['brand'])}</div><div class='small'>{e(v['name'])}<br>{e(v['store'])}</div></td>
<td style='text-align:right;vertical-align:top'><b style='font-size:13pt'>INVOICE</b><div class='mono'>INVOICE {e(t['invoice_number'])}<br>DATE {us(r['d'])} 10:{rng.randint(10,59)} AM<br>ACCOUNT {e(t['account_number'])}<br>PO# {e(t['po_number'])}<br>JOB: UNIT 4 TURNAROUND - PIPE RACK</div></td></tr></table>
<div class='mono' style='border-top:1.2px solid #111;border-bottom:1.2px solid #111;margin-top:8px;padding:3px 0'>SOLD TO: {e(BUYER['name'])} · {e(', '.join(BUYER['addr']))} &nbsp; TERMS: NET 30 &nbsp; CLERK: {rng.randint(100,999)}</div>"""
    th = "<tr><th>Sales No.</th><th>Description</th><th class='r'>Qty</th><th>Size</th><th class='r'>List</th><th class='r'>Your Price</th><th class='r'>Ext Price</th></tr>"
    rows = ''
    for l in r['lines']:
        rows += f"<tr class='nob'><td>{e(l['sales_number'])}</td><td><b>{e(l['description'])}</b>{' &nbsp; ** RETURN **' if l['ret'] else ''}</td><td class='r'>{l['quantity']}</td><td>{e(l['unit'])}</td><td class='r'>{m(l['list'])}</td><td class='r'>{m(l['unit_price'])}</td><td class='r'><b>{m(l['amount'])}</b></td></tr>"
        if l['paint']:
            rows += f"<tr class='sub'><td></td><td colspan='6'>COLOR: {e(l['color_code'])} {e(l['color_name'])} &nbsp; CUSTOM TINT (OZ 32 64 128): {e(l['tint'])}<br>ORDER# {rng.randint(1000000, 9999999)}-{rng.randint(10, 99)} &nbsp; STEWARDSHIP FEE {m(FEE[l['unit']])} X {l['quantity']} = {m(FEE[l['unit']] * l['quantity'])}</td></tr>"
        rows += "<tr><td colspan='7' style='padding:0'></td></tr>"
    tot = f"<tr><td>SUBTOTAL BEFORE FEES</td><td class='r'>{m(r['subtotal'])}</td></tr><tr><td>PAINT STEWARDSHIP FEE</td><td class='r'>{m(r['fee'])}</td></tr><tr><td>SALES TAX {r['rate']*100:.2f}%</td><td class='r'>{m(r['tax'])}</td></tr><tr class='grand'><td>TOTAL USD</td><td class='r'>{m(r['total'])}</td></tr>"
    saved = sum((l['list'] - l['unit_price']) * l['quantity'] for l in r['lines'])
    return f"<html><head><meta charset='utf-8'><style>{CSS}</style></head><body>{head}<table class='items mono tight' style='margin-top:10px'>{th}{rows}</table><table class='totals mono' style='width:50%;margin-left:50%'>{tot}</table><div class='small' style='margin-top:10px'>YOU SAVED {m(saved)} OFF LIST ON THIS INVOICE. Tinted products are not returnable. Colour codes identify the tint, not the product.</div></body></html>"

# ============================================================== SCREENING
SCREENERS = [dict(name='Sentinel Workforce Screening LLC', brand='SENTINEL WORKFORCE SCREENING', addr='10900 Corporate Centre Dr, Houston, TX 77041'),
             dict(name='Meridian Compliance Services Inc.', brand='Meridian Compliance Services', addr='4020 Essen Lane, Baton Rouge, LA 70809')]
SERVICES = [('DT10', 'DRUG SCREEN 10-PANEL URINE (LAB + MRO)', 42.50), ('DT5D', 'DOT 5-PANEL URINE (LAB + MRO)', 48.00), ('BAT1', 'BREATH ALCOHOL TEST', 28.00), ('HAIR', 'HAIR FOLLICLE 5-PANEL', 96.00),
            ('COLL', 'ON-SITE COLLECTION FEE', 18.00), ('NOSH', 'NO-SHOW / CANCELLATION FEE', 22.00), ('BKG3', 'BACKGROUND CHECK - 7 YR COUNTY CRIMINAL', 31.75), ('OFIT', 'RESPIRATOR FIT TEST (QUANT)', 35.00), ('PHYS', 'PHYSICAL EXAM - NON-DOT', 68.00)]
SITES = [('PAS01', 'PASADENA YARD'), ('DPK02', 'DEER PARK UNIT 4'), ('BTR03', 'BATON ROUGE NORTH'), ('LKC04', 'LAKE CHARLES LNG'), ('COR05', 'CORPUS CHRISTI DOCK'), ('BMT06', 'BEAUMONT TERMINAL')]
REASONS = ['PRE', 'RND', 'PA', 'RC', 'FU', 'RTD']

def make_screen(i, tier):
    v = SCREENERS[i % 2]
    svc = rng.sample(SERVICES, rng.randint(4, 7)); sites = rng.sample(SITES, rng.randint(2, 4))
    price = {c: q(p * rng.choice([1, 1, 0.95, 1.08])) for c, _, p in svc}
    month = rng.randint(6, 10); start = dt.date(2026, month, 1); end = dt.date(2026, month + 1, 1) - dt.timedelta(days=1)
    rows = []
    for _ in range(rng.choice([24, 38, 55, 80, 110])):
        c, desc, _p = rng.choice(svc); s = rng.choice(sites)
        rows.append(dict(date=start + dt.timedelta(days=rng.randrange((end - start).days + 1)), donor=f"D{rng.randint(100000, 999999)}", reason=rng.choice(REASONS), code=c, site=s[0], amount=price[c], spec=f"{rng.randint(10000000, 99999999)}"))
    rows.sort(key=lambda x: (x['site'], x['date']))
    summary = []
    for c, desc, _p in svc:
        n = sum(1 for x in rows if x['code'] == c)
        if n: summary.append(dict(service_code=c, description=desc, quantity=n, unit_price=price[c], amount=q(n * price[c])))
    site_tot = [dict(location_code=s[0], name=s[1], amount=sum(x['amount'] for x in rows if x['site'] == s[0])) for s in sites]
    site_tot = [s for s in site_tot if s['amount']]
    fee = q(rng.choice([0, 150, 275]))            # monthly program / consortium fee, not tied to a site
    credit = -q(rng.choice([0, 0, 42.5, 96])) if rng.random() < 0.4 else Decimal('0')
    subtotal = sum(s['amount'] for s in summary)
    total = subtotal + fee + credit
    truth = dict(vendor_name=v['name'], invoice_number=f"SI-{rng.randint(400000, 499999)}", invoice_date=(end + dt.timedelta(days=rng.randint(2, 6))).isoformat(), customer_account=f"C{rng.randint(10000, 99999)}",
                 po_number=f"{rng.randint(4500100000, 4500999999)}", billing_period_start=start.isoformat(), billing_period_end=end.isoformat(),
                 services_subtotal=float(subtotal), program_fee=float(fee), credits_total=float(credit), tax_total=0.0, total=float(total),
                 lines=[dict(service_code=s['service_code'], quantity=s['quantity'], unit_price=float(s['unit_price']), amount=float(s['amount'])) for s in summary],
                 locations=[dict(location_code=s['location_code'], amount=float(s['amount'])) for s in site_tot])
    return dict(id=f'screen-{i:02d}', family='screening', tier=tier, truth=truth, v=v, r=dict(rows=rows, summary=summary, site_tot=site_tot, fee=fee, credit=credit, subtotal=subtotal, total=total, start=start, end=end))

def screen_html(rec):
    v, r, t = rec['v'], rec['r'], rec['truth']
    head = f"""<table><tr><td style='width:58%;vertical-align:top'><div class='brand'>{e(v['brand'])}</div><div class='small'>{e(v['name'])} · {e(v['addr'])}</div></td>
<td style='text-align:right;vertical-align:top'><b style='font-size:13pt'>INVOICE</b><div class='mono'>Invoice # {e(t['invoice_number'])}<br>Invoice date {us(dt.date.fromisoformat(t['invoice_date']))}<br>Account {e(t['customer_account'])}<br>PO {e(t['po_number'])}<br>Service period {us(r['start'])} - {us(r['end'])}</div></td></tr></table>
<div class='mono' style='border-top:1.2px solid #111;border-bottom:1.2px solid #111;margin-top:8px;padding:3px 0'>BILL TO: {e(BUYER['name'])} · {e(', '.join(BUYER['addr']))} · ATTN: ACCOUNTS PAYABLE &nbsp; TERMS NET 30</div>"""
    summ = "<div class='sect'>SUMMARY OF CHARGES</div><table class='items mono tight'><tr><th>Code</th><th>Service</th><th class='r'>Qty</th><th class='r'>Unit price</th><th class='r'>Amount</th></tr>" + \
           ''.join(f"<tr><td>{e(s['service_code'])}</td><td>{e(s['description'])}</td><td class='r'>{s['quantity']}</td><td class='r'>{m(s['unit_price'])}</td><td class='r'>{m(s['amount'])}</td></tr>" for s in r['summary']) + '</table>'
    loc = "<div class='sect'>CHARGES BY LOCATION</div><table class='items mono tight' style='width:60%'><tr><th>Location</th><th>Name</th><th class='r'>Tests</th><th class='r'>Amount</th></tr>" + \
          ''.join(f"<tr><td>{e(s['location_code'])}</td><td>{e(s['name'])}</td><td class='r'>{sum(1 for x in r['rows'] if x['site']==s['location_code'])}</td><td class='r'>{m(s['amount'])}</td></tr>" for s in r['site_tot']) + '</table>'
    tot = f"<tr><td>Services subtotal</td><td class='r'>{m(r['subtotal'])}</td></tr>" + (f"<tr><td>Monthly program administration fee</td><td class='r'>{m(r['fee'])}</td></tr>" if r['fee'] else '') + \
          (f"<tr><td>Credit - duplicate collection billed on prior invoice</td><td class='r'>{m(r['credit'])}</td></tr>" if r['credit'] else '') + f"<tr><td>Sales tax</td><td class='r'>0.00</td></tr><tr class='grand'><td>TOTAL DUE USD</td><td class='r'>{m(r['total'])}</td></tr>"
    detail = "<div class='pb'></div>"; names = dict(SITES); per = 46; rows = r['rows']
    th = "<tr><th>Date</th><th>Donor ID</th><th>Specimen</th><th>Reason</th><th>Code</th><th>Site</th><th class='r'>Charge</th></tr>"
    for k in range(0, len(rows), per):
        if k: detail += "<div class='pb'></div>"
        detail += f"<div class='mono'>{e(v['brand'])} · Invoice # {e(t['invoice_number'])} · DETAIL OF SERVICES · page {k//per + 2}</div><table class='items mono tight'>{th}"
        prev = rows[k - 1]['site'] if k else None
        for x in rows[k:k + per]:
            if x['site'] != prev:
                detail += f"<tr><td colspan='7' style='background:#eef1f4'><b>{e(x['site'])} {e(names[x['site']])}</b></td></tr>"; prev = x['site']
            detail += f"<tr><td>{us(x['date'])}</td><td>{e(x['donor'])}</td><td>{e(x['spec'])}</td><td>{e(x['reason'])}</td><td>{e(x['code'])}</td><td>{e(x['site'])}</td><td class='r'>{m(x['amount'])}</td></tr>"
        detail += '</table>'
    return f"<html><head><meta charset='utf-8'><style>{CSS}</style></head><body>{head}{summ}{loc}<table class='totals mono' style='width:56%;margin-left:44%'>{tot}</table><div class='small' style='margin-top:8px'>Reason codes: PRE pre-employment, RND random, PA post-accident, RC reasonable cause, FU follow-up, RTD return to duty. Donor names are withheld from invoices; match on donor ID.</div>{detail}</body></html>"

# ============================================================== main
def main():
    os.makedirs(OUT, exist_ok=True)
    for f in glob.glob(os.path.join(OUT, '*')): os.remove(f)
    recs = [make_rental(i, 'scan' if i % 3 == 0 else 'digital') for i in range(1, 19)]
    recs += [make_paint(i, 'scan' if i % 3 == 0 else 'digital') for i in range(1, 13)]
    recs += [make_screen(i, 'scan' if i % 4 == 0 else 'digital') for i in range(1, 11)]
    key, rows = {}, []
    for rec in recs:
        pdf = os.path.join(OUT, rec['id'] + '.pdf')
        A.to_pdf({'rental': rental_html, 'paint': paint_html, 'screening': screen_html}[rec['family']](rec), pdf)
        if rec['tier'] == 'scan': rec['kind'] = 'hard'; A.scan(pdf, rec)
        pages = fitz.open(pdf).page_count
        key[rec['id']] = dict(family=rec['family'], tier=rec['tier'], scanned=rec['tier'] == 'scan', pages=pages, line_count=len(rec['truth']['lines']), truth=rec['truth'])
        rows.append([rec['id'], rec['family'], rec['tier'], pages, len(rec['truth']['lines'])])
        print(*rows[-1])
    json.dump(key, open(os.path.join(HERE, 'answer-key-b.json'), 'w'), indent=1)
    with open(os.path.join(HERE, 'manifest-b.csv'), 'w', newline='') as f:
        w = csv.writer(f); w.writerow(['id', 'family', 'tier', 'pages', 'lines']); w.writerows(rows)

if __name__ == '__main__':
    main()
