#!/usr/bin/env python3
"""Generate the Pondero Labs document-extraction test set.

60 documents we wrote ourselves (no real companies, no personal data):
  45 invoices / credit notes  - 15 clean digital PDFs, 15 scans, 15 with a known trap
  15 service agreements       - 10 digital PDFs, 5 scans
Every value in the answer key comes from the same record that renders the page,
so the key is exact by construction.

Usage:  venv/bin/python gen.py     -> docs/*.pdf, answer-key.json, manifest.csv
"""
import csv, datetime as dt, html, io, json, os, random, subprocess, sys, glob
from decimal import Decimal, ROUND_HALF_UP

import fitz  # PyMuPDF
import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, 'docs')
SEED = 20261201
rng = random.Random(SEED)
BUYER = {'name': 'Halden Row Ltd', 'addr': ['14 Carrow Quay', 'Bristol BS1 6QD', 'United Kingdom'], 'vat': 'GB 318 4471 09'}

D2 = Decimal('0.01')
def q(x): return Decimal(x).quantize(D2, rounding=ROUND_HALF_UP)

# ---------------------------------------------------------------- vendors
# brand = what the logo says; name = the legal entity (ground truth for vendor_name)
VENDORS = [
    dict(name='Castellan Freight Services Inc.', brand='Castellan Freight', country='US', lang='en', cur='USD', sym='$', num='us', date='us_long', tax=('Sales tax', [Decimal('0.0725')]), addr=['2210 Harbor Gate Blvd', 'Oakland, CA 94607', 'United States'], id='EIN 84-2219930'),
    dict(name='Marlowe & Finch Consulting LLC', brand='Marlowe & Finch', country='US', lang='en', cur='USD', sym='$', num='us', date='us_slash', tax=('Sales tax', [Decimal('0')]), addr=['88 Pine Street, Floor 9', 'New York, NY 10005', 'United States'], id='EIN 47-3301128'),
    dict(name='Quillhaven Software Ltd', brand='Quillhaven', country='GB', lang='en', cur='GBP', sym='£', num='us', date='gb_slash', tax=('VAT', [Decimal('0.20')]), addr=['3 Tanners Yard', 'Leeds LS2 7EY', 'United Kingdom'], id='VAT GB 204 5518 37'),
    dict(name='Brightleaf Supply Co. Ltd', brand='BRIGHTLEAF', country='GB', lang='en', cur='GBP', sym='£', num='us', date='gb_long', tax=('VAT', [Decimal('0.20'), Decimal('0.05')]), addr=['Unit 12, Meridian Trade Park', 'Reading RG2 0TD', 'United Kingdom'], id='VAT GB 187 2260 54'),
    dict(name='Nordwerk Maschinenbau GmbH', brand='NORDWERK', country='DE', lang='de', cur='EUR', sym='€', num='de', date='de_dot', tax=('USt.', [Decimal('0.19')]), addr=['Speicherstraße 41', '28217 Bremen', 'Deutschland'], id='USt-IdNr. DE 298 441 173'),
    dict(name='Lindenhof Bürobedarf GmbH & Co. KG', brand='Lindenhof', country='DE', lang='de', cur='EUR', sym='€', num='de', date='de_dot', tax=('USt.', [Decimal('0.19'), Decimal('0.07')]), addr=['Am Güterbahnhof 6', '90443 Nürnberg', 'Deutschland'], id='USt-IdNr. DE 811 207 465'),
    dict(name='Atelier Verrier SAS', brand='Atelier Verrier', country='FR', lang='fr', cur='EUR', sym='€', num='fr', date='gb_slash', tax=('TVA', [Decimal('0.20')]), addr=['27 rue des Tanneurs', '69009 Lyon', 'France'], id='TVA FR 61 882 104 337'),
    dict(name='Soluciones Tramontana S.L.', brand='Tramontana', country='ES', lang='es', cur='EUR', sym='€', num='de', date='gb_slash', tax=('IVA', [Decimal('0.21')]), addr=['Carrer de la Llacuna 118', '08018 Barcelona', 'España'], id='NIF B-66401927'),
    dict(name='Kestrel Ridge Analytics Inc.', brand='Kestrel Ridge', country='CA', lang='en', cur='CAD', sym='$', num='us', date='iso', tax=('GST/HST', [Decimal('0.13')]), addr=['410 Wellington St W, Suite 300', 'Toronto, ON M5V 1E3', 'Canada'], id='GST/HST 81234 5567 RT0001'),
    dict(name='Wattlebird Logistics Pty Ltd', brand='Wattlebird', country='AU', lang='en', cur='AUD', sym='$', num='us', date='gb_slash', tax=('GST', [Decimal('0.10')]), addr=['19 Dockside Road', 'Port Melbourne VIC 3207', 'Australia'], id='ABN 53 104 882 716'),
    dict(name='Fjällbacka Konsult AB', brand='Fjällbacka Konsult', country='SE', lang='en', cur='SEK', sym='kr', num='fr', date='iso', tax=('VAT (moms)', [Decimal('0.25')]), addr=['Hamngatan 22', '411 14 Göteborg', 'Sweden'], id='VAT SE556812340901'),
    dict(name='Rheintal Präzision AG', brand='Rheintal Präzision', country='CH', lang='de', cur='CHF', sym='CHF', num='ch', date='de_dot', tax=('MWST', [Decimal('0.081')]), addr=['Industriestrasse 9', '9430 St. Margrethen', 'Schweiz'], id='CHE-112.604.918 MWST'),
    dict(name='Osprey Point Facilities Ltd', brand='Osprey Point', country='IE', lang='en', cur='EUR', sym='€', num='us', date='gb_long', tax=('VAT', [Decimal('0.23')]), addr=['Block C, Eastgate Avenue', 'Little Island, Cork T45 XN29', 'Ireland'], id='VAT IE 3482291KH'),
    dict(name='Tidewater Print & Pack LLC', brand='Tidewater Print', country='US', lang='en', cur='USD', sym='$', num='us', date='us_slash', tax=('Sales tax', [Decimal('0.06')]), addr=['741 Granby Street', 'Norfolk, VA 23510', 'United States'], id='EIN 54-1907762'),
    dict(name='Halcyon Cloud Hosting B.V.', brand='halcyon.cloud', country='NL', lang='en', cur='EUR', sym='€', num='de', date='iso', tax=('VAT (btw)', [Decimal('0.21')]), addr=['Kabelweg 57', '1014 BA Amsterdam', 'Netherlands'], id='VAT NL 8617.40.221.B01'),
]

ITEMS = {
    'en': [('Freight forwarding, pallet', 148.00), ('Warehouse handling fee', 62.50), ('Consulting, senior analyst (day)', 1150.00), ('Software licence, annual seat', 420.00), ('Onboarding workshop', 1800.00), ('Printed cartons, 400x300x200', 1.84), ('Support plan, monthly', 349.00), ('Data migration (hour)', 135.00), ('Customs clearance', 95.00), ('Site survey', 640.00), ('Replacement filter set', 78.40), ('Managed backup, per TB', 21.00), ('Courier, next day', 28.75), ('Security review', 2400.00), ('Training seat', 310.00)],
    'de': [('Frästeil nach Zeichnung', 214.60), ('Montagepauschale', 890.00), ('Kopierpapier A4, 80 g (Karton)', 24.90), ('Wartungsvertrag, Quartal', 1260.00), ('Ersatzdichtung DN50', 13.75), ('Anfahrt und Rüstzeit', 185.00), ('Tonerkartusche schwarz', 67.20), ('Kalibrierung Messmittel', 320.00), ('Fachbuch (ermäßigter Satz)', 39.80), ('Schulung vor Ort (Tag)', 1450.00)],
    'fr': [('Vitrage trempé 8 mm (m²)', 96.40), ('Pose et réglage', 540.00), ('Déplacement', 85.00), ('Miroir sur mesure', 312.00), ('Joint silicone (lot)', 18.90), ('Étude technique', 760.00)],
    'es': [('Licencia de software, anual', 380.00), ('Horas de consultoría', 95.00), ('Mantenimiento mensual', 240.00), ('Migración de datos', 1250.00), ('Formación presencial (día)', 890.00), ('Soporte prioritario', 160.00)],
}
L = {
    'en': dict(invoice='INVOICE', credit='CREDIT NOTE', no='Invoice no.', cno='Credit note no.', date='Invoice date', due='Due date', po='PO number', billto='Bill to', desc='Description', qty='Qty', unit='Unit price', amount='Amount', sub='Subtotal', total='Total', terms='Payment terms', paid='Amount paid', bal='Balance due', disc='Discount', ship='Shipping', page='Page', cont='continued on next page', acct='Customer account', quote='Quote ref.', orig='Refers to invoice', bank='Bank details'),
    'de': dict(invoice='RECHNUNG', credit='GUTSCHRIFT', no='Rechnungsnr.', cno='Gutschriftsnr.', date='Rechnungsdatum', due='Fällig am', po='Bestellnummer', billto='Rechnungsempfänger', desc='Bezeichnung', qty='Menge', unit='Einzelpreis', amount='Betrag', sub='Nettobetrag', total='Gesamtbetrag', terms='Zahlungsbedingungen', paid='Bereits gezahlt', bal='Offener Betrag', disc='Rabatt', ship='Versand', page='Seite', cont='Fortsetzung auf der nächsten Seite', acct='Kundennummer', quote='Angebotsnr.', orig='Bezug auf Rechnung', bank='Bankverbindung'),
    'fr': dict(invoice='FACTURE', credit='AVOIR', no='Facture n°', cno='Avoir n°', date='Date de facture', due="Date d'échéance", po='Bon de commande', billto='Facturé à', desc='Désignation', qty='Qté', unit='Prix unitaire', amount='Montant', sub='Total HT', total='Total TTC', terms='Conditions de paiement', paid='Acompte versé', bal='Reste à payer', disc='Remise', ship='Livraison', page='Page', cont='suite page suivante', acct='Compte client', quote='Devis n°', orig='Facture concernée', bank='Coordonnées bancaires'),
    'es': dict(invoice='FACTURA', credit='FACTURA RECTIFICATIVA', no='N.º de factura', cno='N.º de rectificativa', date='Fecha de factura', due='Fecha de vencimiento', po='N.º de pedido', billto='Facturar a', desc='Concepto', qty='Cant.', unit='Precio unitario', amount='Importe', sub='Base imponible', total='Total', terms='Condiciones de pago', paid='Importe pagado', bal='Saldo pendiente', disc='Descuento', ship='Envío', page='Página', cont='continúa en la página siguiente', acct='Cuenta de cliente', quote='N.º de presupuesto', orig='Factura de referencia', bank='Datos bancarios'),
}
MONTHS = {'en': 'January February March April May June July August September October November December'.split()}

def fmt_num(x, style):
    x = q(x); neg = x < 0; s = f'{abs(x):,.2f}'
    if style == 'de': s = s.replace(',', 'X').replace('.', ',').replace('X', '.')
    elif style == 'fr': s = s.replace(',', ' ').replace('.', ',')
    elif style == 'ch': s = s.replace(',', "'")
    return ('-' if neg else '') + s

def money(x, v):
    n = fmt_num(x, v['num'])
    if v['sym'] in ('kr', 'CHF') or v['num'] in ('de', 'fr'):
        return f"{n} {v['sym']}" if v['sym'] != 'CHF' else f"CHF {n}"
    return (f"-{v['sym']}{n[1:]}" if n.startswith('-') else f"{v['sym']}{n}")

def fmt_date(d, style):
    if style == 'us_long': return f"{MONTHS['en'][d.month-1]} {d.day}, {d.year}"
    if style == 'gb_long': return f"{d.day} {MONTHS['en'][d.month-1]} {d.year}"
    if style == 'us_slash': return d.strftime('%m/%d/%Y')
    if style == 'gb_slash': return d.strftime('%d/%m/%Y')
    if style == 'de_dot': return d.strftime('%d.%m.%Y')
    return d.isoformat()

def rand_date(lo=dt.date(2026, 6, 1), hi=dt.date(2026, 11, 20)):
    return lo + dt.timedelta(days=rng.randrange((hi - lo).days))

def ambiguous_date():
    """A date whose day and month are both <= 12 and differ, so MM/DD vs DD/MM matters."""
    while True:
        d = rand_date()
        if d.day <= 12 and d.day != d.month: return d

# ---------------------------------------------------------------- invoices
TRAPS = ['euro_number_format', 'ambiguous_date', 'due_from_terms', 'credit_note', 'no_po_decoy_refs',
         'two_tax_rates', 'deposit_balance_due', 'two_pages', 'brand_vs_legal_name', 'dollar_not_usd',
         'non_english', 'discount_and_shipping', 'krona_currency', 'swiss_format', 'account_no_decoy']

def make_invoice(i, tier, trap=None):
    by = {v['brand']: v for v in VENDORS}
    pick = {
        'euro_number_format': ['Tramontana', 'halcyon.cloud'], 'ambiguous_date': ['Quillhaven', 'Wattlebird'], 'credit_note': ['Atelier Verrier', 'Quillhaven'],
        'two_tax_rates': ['BRIGHTLEAF', 'Lindenhof'], 'brand_vs_legal_name': ['BRIGHTLEAF', 'halcyon.cloud'], 'dollar_not_usd': ['Kestrel Ridge', 'Wattlebird'],
        'non_english': ['NORDWERK', 'Atelier Verrier', 'Tramontana'], 'krona_currency': ['Fjällbacka Konsult'], 'swiss_format': ['Rheintal Präzision'],
    }
    if trap in pick: v = by[rng.choice(pick[trap])]
    elif tier in ('clean', 'scan'): v = rng.choice([x for x in VENDORS if x['lang'] == 'en' and x['country'] in ('US', 'GB', 'IE')])
    else: v = rng.choice(VENDORS)
    lab = L[v['lang']]
    n_items = rng.randint(2, 6) if trap != 'two_pages' else rng.randint(31, 38)
    pool = ITEMS[v['lang']]
    lines = []
    for k in range(n_items):
        desc, price = pool[k % len(pool)] if trap == 'two_pages' else rng.choice(pool)
        if trap == 'two_pages': desc = f'{desc} ({k+1:02d})'
        qty = rng.choice([1, 1, 2, 3, 4, 5]) if price > 250 else rng.choice([1, 2, 3, 4, 5, 8, 10, 12, 24, 40])
        lines.append([desc, qty, q(price * rng.choice([1, 1, 1, 0.9, 1.1, 1.25]))])
    rates = v['tax'][1]
    if trap == 'two_tax_rates':
        assert len(rates) == 2
    else:
        rates = rates[:1]
    # assign each line a rate
    for k, ln in enumerate(lines): ln.append(rates[k % len(rates)] if len(rates) > 1 else rates[0])
    credit = trap == 'credit_note'
    sign = -1 if credit else 1
    line_amounts = [q(ln[1] * ln[2]) for ln in lines]
    goods = sum(line_amounts)
    discount = q(goods * Decimal('0.05')) if trap == 'discount_and_shipping' else Decimal('0')
    shipping = q(rng.choice([18, 35, 60, 120])) if trap == 'discount_and_shipping' else Decimal('0')
    subtotal = goods - discount + shipping
    # tax per rate (discount/shipping taxed at the first rate)
    tax_by = {}
    for ln, amt in zip(lines, line_amounts): tax_by[ln[3]] = tax_by.get(ln[3], Decimal('0')) + amt
    tax_by[rates[0]] = tax_by[rates[0]] - discount + shipping
    tax_rows = [(r, q(base * r)) for r, base in tax_by.items()]
    tax_total = sum(t for _, t in tax_rows)
    total = subtotal + tax_total
    inv_date = ambiguous_date() if trap == 'ambiguous_date' else rand_date()
    net_days = rng.choice([14, 30, 30, 45, 60])
    due = inv_date + dt.timedelta(days=net_days)
    if trap == 'ambiguous_date':
        # keep the due date unambiguous (day > 12) so the page itself reveals the DD/MM order
        while due.day <= 12: due += dt.timedelta(days=1)
    prefix = rng.choice(['INV-', 'RE-', 'F', 'SI-', '', 'IN/']) if not credit else rng.choice(['CN-', 'AV-', 'GS-'])
    number = f"{prefix}{rng.randint(2026, 2026)}{rng.choice(['-', '/', ''])}{rng.randint(1000, 98999):05d}"
    has_po = trap != 'no_po_decoy_refs' and rng.random() < 0.75
    po = f"PO-{rng.randint(41000, 49999)}" if has_po else None
    deposit = q(total * Decimal('0.4')) if trap == 'deposit_balance_due' else Decimal('0')
    rec = dict(
        id=f'inv-{i:02d}', kind='invoice', tier=tier, trap=trap or '', lang=v['lang'], country=v['country'], vendor=v,
        truth=dict(vendor_name=v['name'], invoice_number=number, invoice_date=inv_date.isoformat(), due_date=due.isoformat(), currency=v['cur'],
                   subtotal=float(sign * subtotal), tax_total=float(sign * tax_total), total=float(sign * total), po_number=po,
                   document_type='credit_note' if credit else 'invoice', line_item_count=n_items),
        render=dict(lines=lines, line_amounts=line_amounts, discount=discount, shipping=shipping, subtotal=subtotal, tax_rows=tax_rows, total=total,
                    sign=sign, inv_date=inv_date, due=due, net_days=net_days, deposit=deposit, number=number, po=po, lab=lab,
                    layout=rng.choice(['a', 'b', 'c']), show_due=trap != 'due_from_terms',
                    acct=f"{rng.randint(100000, 999999)}", quote=f"Q-{rng.randint(7000, 9999)}",
                    orig=f"INV-2026-{rng.randint(1000, 9999)}" if credit else None))
    return rec

CSS = """
@page { size: A4; margin: 16mm 15mm 18mm 15mm; }
* { box-sizing: border-box; }
body { font-family: 'Liberation Sans', 'DejaVu Sans', Arial, sans-serif; font-size: 10.5pt; color: #1b1f24; margin: 0; }
.serif { font-family: 'Liberation Serif', 'DejaVu Serif', serif; }
h1 { font-size: 21pt; letter-spacing: .06em; margin: 0; }
.brand { font-size: 17pt; font-weight: 700; }
.muted { color: #5b6470; font-size: 9pt; }
table { border-collapse: collapse; width: 100%; }
.items th { text-align: left; font-size: 8.5pt; text-transform: uppercase; letter-spacing: .05em; border-bottom: 1.5px solid #1b1f24; padding: 5px 6px; }
.items td { padding: 5px 6px; border-bottom: 1px solid #d8dde3; vertical-align: top; }
.r { text-align: right; white-space: nowrap; }
.meta td { padding: 2px 0; } .meta td:first-child { color: #5b6470; padding-right: 14px; }
.totals { width: 46%; margin-left: 54%; margin-top: 10px; } .totals td { padding: 4px 6px; }
.totals .grand td { font-weight: 700; border-top: 1.5px solid #1b1f24; font-size: 12pt; }
.box { border: 1px solid #b9c0c8; padding: 9px 11px; }
.foot { margin-top: 46px; font-size: 8pt; color: #5b6470; border-top: 1px solid #d8dde3; padding-top: 4px; }
.pb { page-break-after: always; }
.band { background: #1f3a4d; color: #fff; padding: 12px 14px; } .band .muted { color: #c9d6df; }
.contract p { text-align: justify; line-height: 1.42; margin: 0 0 7px; } .contract h2 { font-size: 11pt; margin: 12px 0 4px; }
"""

def e(s): return html.escape(str(s))

def invoice_html(rec):
    v, r, lab = rec['vendor'], rec['render'], rec['render']['lab']
    credit = rec['truth']['document_type'] == 'credit_note'
    s = r['sign']
    title = lab['credit'] if credit else lab['invoice']
    trap = rec['trap']
    show_legal_in_header = trap != 'brand_vs_legal_name'
    terms = {'en': f"Net {r['net_days']} days from invoice date", 'de': f"Zahlbar innerhalb von {r['net_days']} Tagen ab Rechnungsdatum ohne Abzug",
             'fr': f"Paiement à {r['net_days']} jours date de facture", 'es': f"Pago a {r['net_days']} días fecha de factura"}[rec['lang']]
    meta = [(lab['cno'] if credit else lab['no'], r['number']), (lab['date'], fmt_date(r['inv_date'], v['date']))]
    if r['show_due']: meta.append((lab['due'], fmt_date(r['due'], v['date'])))
    if r['po']: meta.append((lab['po'], r['po']))
    if trap in ('no_po_decoy_refs',): meta += [(lab['quote'], r['quote']), (lab['acct'], r['acct'])]
    if trap == 'account_no_decoy': meta.insert(0, (lab['acct'], r['acct']))
    if r['orig']: meta.append((lab['orig'], r['orig']))
    meta.append((lab['terms'], terms))
    meta_html = '<table class="meta" style="width:auto">' + ''.join(f'<tr><td>{e(a)}</td><td><b>{e(b)}</b></td></tr>' for a, b in meta) + '</table>'
    vend_block = f"<div class='brand'>{e(v['brand'])}</div>" + (f"<div>{e(v['name'])}</div>" if show_legal_in_header else '') + ''.join(f"<div class='muted'>{e(a)}</div>" for a in v['addr'])
    bill = f"<div class='muted'>{e(lab['billto'])}</div><b>{e(BUYER['name'])}</b>" + ''.join(f"<div>{e(a)}</div>" for a in BUYER['addr']) + f"<div class='muted'>VAT {e(BUYER['vat'])}</div>"
    two_rates = len(r['tax_rows']) > 1
    def rows(lines, amts):
        out = ''
        for ln, amt in zip(lines, amts):
            rate = f"<td class='r'>{fmt_num(ln[3]*100, v['num']).rstrip('0').rstrip(',.')}%</td>" if two_rates else ''
            out += f"<tr><td>{e(ln[0])}</td><td class='r'>{ln[1]}</td><td class='r'>{money(ln[2], v)}</td>{rate}<td class='r'>{money(s*amt, v)}</td></tr>"
        return out
    head = f"<tr><th>{e(lab['desc'])}</th><th class='r'>{e(lab['qty'])}</th><th class='r'>{e(lab['unit'])}</th>{'<th class=r>'+e(v['tax'][0])+'</th>' if two_rates else ''}<th class='r'>{e(lab['amount'])}</th></tr>"
    tot = ''
    if r['discount']: tot += f"<tr><td>{e(lab['disc'])} 5%</td><td class='r'>{money(-r['discount'], v)}</td></tr>"
    if r['shipping']: tot += f"<tr><td>{e(lab['ship'])}</td><td class='r'>{money(r['shipping'], v)}</td></tr>"
    tot += f"<tr><td>{e(lab['sub'])}</td><td class='r'>{money(s*r['subtotal'], v)}</td></tr>"
    for rate, t in r['tax_rows']:
        pct = fmt_num(rate*100, v['num']).rstrip('0').rstrip(',.')
        tot += f"<tr><td>{e(v['tax'][0])} {pct}%</td><td class='r'>{money(s*t, v)}</td></tr>"
    tot += f"<tr class='grand'><td>{e(lab['total'])}{' '+v['cur'] if rec['trap'] in ('dollar_not_usd',) and rec['id'][-1] in '02468' else ''}</td><td class='r'>{money(s*r['total'], v)}</td></tr>"
    if r['deposit']:
        tot += f"<tr><td>{e(lab['paid'])}</td><td class='r'>{money(-r['deposit'], v)}</td></tr><tr><td><b>{e(lab['bal'])}</b></td><td class='r'><b style='font-size:13pt'>{money(r['total']-r['deposit'], v)}</b></td></tr>"
    foot = f"<div class='foot'>{e(v['name'])} · {e(', '.join(v['addr']))} · {e(v['id'])} · {e(lab['bank'])}: IBAN XX00 0000 0000 0000 0000 00</div>"
    lay = r['layout']
    if lay == 'a':
        top = f"<table><tr><td style='width:55%;vertical-align:top'>{vend_block}</td><td style='vertical-align:top;text-align:right'><h1>{e(title)}</h1></td></tr></table><table style='margin-top:18px'><tr><td style='width:50%;vertical-align:top'>{bill}</td><td style='vertical-align:top'>{meta_html}</td></tr></table>"
    elif lay == 'b':
        top = f"<div class='band'><table><tr><td>{vend_block.replace('muted', 'muted')}</td><td style='text-align:right'><h1 class='serif'>{e(title)}</h1></td></tr></table></div><table style='margin-top:16px'><tr><td style='width:48%;vertical-align:top'><div class='box'>{bill}</div></td><td style='width:4%'></td><td style='vertical-align:top'><div class='box'>{meta_html}</div></td></tr></table>"
    else:
        top = f"<div style='text-align:center'>{vend_block}</div><hr><h1 class='serif' style='margin:8px 0 12px'>{e(title)}</h1><table><tr><td style='width:55%;vertical-align:top'>{meta_html}</td><td style='vertical-align:top'>{bill}</td></tr></table>"
    lines, amts = r['lines'], r['line_amounts']
    if rec['trap'] == 'two_pages':
        cut = 22
        body = f"<table class='items' style='margin-top:18px'>{head}{rows(lines[:cut], amts[:cut])}</table><div class='muted' style='text-align:right;margin-top:6px'>{e(lab['page'])} 1/2 · {e(lab['cont'])}</div><div class='pb'></div>" \
               f"<div class='muted'>{e(v['brand'])} · {e(title)} {e(r['number'])} · {e(lab['page'])} 2/2</div><table class='items' style='margin-top:8px'>{head}{rows(lines[cut:], amts[cut:])}</table>"
    else:
        body = f"<table class='items' style='margin-top:18px'>{head}{rows(lines, amts)}</table>"
    return f"<html><head><meta charset='utf-8'><style>{CSS}</style></head><body>{top}{body}<table class='totals'>{tot}</table>{foot}</body></html>"

# ---------------------------------------------------------------- contracts
PROVIDERS = ['Quillhaven Software Ltd', 'Halcyon Cloud Hosting B.V.', 'Marlowe & Finch Consulting LLC', 'Kestrel Ridge Analytics Inc.', 'Osprey Point Facilities Ltd', 'Fjällbacka Konsult AB', 'Castellan Freight Services Inc.']
CUSTOMERS = ['Halden Row Ltd', 'Pemberley Outdoor Supply Co.', 'Greywether Insurance Group plc', 'Arden Vale Foods Limited', 'Sablewood Clinics Inc.', 'Tarn & Fell Brewing Ltd', 'Corvid Lane Media GmbH']
LAWS = [('England and Wales', 'the courts of England and Wales'), ('the State of New York', 'the state and federal courts located in New York County'), ('the State of Delaware', 'the courts of the State of Delaware'),
        ('Ireland', 'the courts of Ireland'), ('the Province of Ontario', 'the courts of Ontario'), ('the State of California', 'the courts of San Francisco County, California'), ('the Netherlands', 'the competent court in Amsterdam')]
WORDS = {12: 'twelve', 24: 'twenty-four', 36: 'thirty-six', 30: 'thirty', 45: 'forty-five', 60: 'sixty', 90: 'ninety', 1: 'one', 2: 'two', 3: 'three', 5: 'five', 14: 'fourteen', 120: 'one hundred and twenty'}
CTRAPS = ['effective_last_signature', 'term_in_years', 'amendment_overrides_term', 'venue_differs_from_law', 'no_auto_renew', 'fixed_cap', 'notice_in_months', 'effective_last_signature', 'term_in_years', 'fixed_cap']

def make_contract(i, tier, trap=None):
    prov, cust = rng.choice(PROVIDERS), rng.choice(CUSTOMERS)
    law, venue = rng.choice(LAWS)
    term = rng.choice([12, 24, 36])
    notice = rng.choice([30, 60, 90])
    pay = rng.choice([30, 45, 60])
    auto = trap != 'no_auto_renew'
    eff = rand_date(dt.date(2026, 1, 10), dt.date(2026, 10, 30))
    sig1 = eff - dt.timedelta(days=rng.randint(4, 11)); sig2 = eff
    cap_fixed = trap == 'fixed_cap'
    cap_amt = rng.choice([100000, 250000, 500000, 1000000]) if cap_fixed else None
    cur = rng.choice(['USD', 'GBP', 'EUR'])
    stated_term = term
    if trap == 'amendment_overrides_term':
        stated_term = rng.choice([t for t in (12, 24, 36) if t != term])
    if trap == 'venue_differs_from_law':
        venue = rng.choice([vn for lw, vn in LAWS if lw != law])
    notice_months = None
    if trap == 'notice_in_months':
        notice_months = rng.choice([2, 3]); notice = notice_months * 30
    truth = dict(provider_name=prov, customer_name=cust, effective_date=eff.isoformat(), initial_term_months=term, auto_renews=auto,
                 renewal_notice_days=(notice if auto else None), governing_law=law.replace('the ', '', 1) if law.startswith('the ') else law,
                 payment_terms_days=pay, liability_cap_type='fixed_amount' if cap_fixed else 'fees_paid_12_months', liability_cap_amount=(float(cap_amt) if cap_fixed else None))
    return dict(id=f'con-{i:02d}', kind='contract', tier=tier, trap=trap or '', lang='en', country='', truth=truth,
                render=dict(prov=prov, cust=cust, law=law, venue=venue, term=term, stated_term=stated_term, notice=notice, notice_months=notice_months, pay=pay, auto=auto,
                            eff=eff, sig1=sig1, sig2=sig2, cap_amt=cap_amt, cur=cur, ref=f"MSA-{rng.randint(2200, 9800)}", fee=rng.choice([18000, 42000, 96000, 150000])))

def contract_html(rec):
    r, trap = rec['render'], rec['trap']
    long = lambda d: f"{d.day} {MONTHS['en'][d.month-1]} {d.year}"
    if trap == 'effective_last_signature':
        eff_txt = 'This Agreement takes effect on the date of the last signature below (the "Effective Date").'
        intro_date = f"dated for reference {long(r['sig1'] - dt.timedelta(days=9))}"
    else:
        eff_txt = f'This Agreement takes effect on {long(r["eff"])} (the "Effective Date").'
        intro_date = f"prepared {long(r['sig1'] - dt.timedelta(days=9))}"
    st = r['stated_term']
    if trap == 'term_in_years':
        term_txt = f"{WORDS[st//12]} ({st//12}) year{'s' if st > 12 else ''}"
    else:
        term_txt = f"{WORDS[st]} ({st}) months"
    if r['auto']:
        n = f"{WORDS[r['notice_months']]} ({r['notice_months']}) months'" if r['notice_months'] else f"{WORDS[r['notice']]} ({r['notice']}) days'"
        renew = f"Upon expiry of the Initial Term this Agreement shall renew automatically for successive periods of twelve (12) months (each a \"Renewal Term\") unless either party gives the other written notice of non-renewal at least {n} before the end of the then-current term."
        if r['notice_months']: renew += ' For the purposes of this clause a month is deemed to be thirty (30) days.'
    else:
        renew = 'This Agreement shall expire at the end of the Initial Term and shall not renew automatically. Any extension requires a written agreement signed by both parties.'
    sym = {'USD': 'USD', 'GBP': 'GBP', 'EUR': 'EUR'}[r['cur']]
    if r['cap_amt']:
        cap = f"Subject to clause 8.3, each party's total aggregate liability arising out of or in connection with this Agreement shall not exceed {sym} {r['cap_amt']:,.0f}."
    else:
        cap = "Subject to clause 8.3, each party's total aggregate liability arising out of or in connection with this Agreement shall not exceed the total Fees paid or payable by the Customer in the twelve (12) months immediately preceding the event giving rise to the claim."
    amend = ''
    if trap == 'amendment_overrides_term':
        amend = f"<h2>12. Special terms</h2><p>12.1 Notwithstanding clause 3.1, the parties agree that the Initial Term shall be {WORDS[r['term']]} ({r['term']}) months from the Effective Date. In the event of conflict, this clause 12 prevails over the remainder of this Agreement.</p>"
    fill = ("The Provider shall perform the Services with reasonable skill and care and in accordance with the Service Levels set out in Schedule 2. "
            "The Customer shall provide such access, information and co-operation as the Provider reasonably requires. ")
    body = f"""
<div class='contract serif'>
<div style='text-align:center'><div class='muted'>Agreement reference {e(r['ref'])} · {intro_date}</div><h1 style='font-size:17pt;margin:8px 0 14px'>MASTER SERVICES AGREEMENT</h1></div>
<p>This Master Services Agreement (the "Agreement") is made between <b>{e(r['prov'])}</b> (the "Provider") and <b>{e(r['cust'])}</b> (the "Customer"), each a "party" and together the "parties".</p>
<h2>1. Definitions</h2><p>1.1 "Fees" means the charges set out in the applicable Order Form. "Services" means the services described in Schedule 1. "Confidential Information" has the meaning given in clause 7.</p>
<h2>2. Commencement</h2><p>2.1 {eff_txt}</p>
<h2>3. Term and renewal</h2><p>3.1 This Agreement shall continue for an initial term of {term_txt} from the Effective Date (the "Initial Term"), unless terminated earlier in accordance with clause 9.</p><p>3.2 {renew}</p>
<h2>4. Services</h2><p>4.1 {fill}</p><p>4.2 {fill}Changes to the Services shall be agreed in writing through the change procedure in Schedule 3.</p>
<h2>5. Fees and payment</h2><p>5.1 The annual Fees are {sym} {r['fee']:,.0f}, exclusive of applicable taxes, invoiced annually in advance.</p><p>5.2 The Customer shall pay each undisputed invoice within {WORDS[r['pay']]} ({r['pay']}) days of the date of invoice. Interest on late payment accrues at four per cent (4%) per annum above the base rate.</p>
<h2>6. Data protection</h2><p>6.1 Each party shall comply with applicable data protection law. The data processing terms in Schedule 4 apply where the Provider processes personal data on behalf of the Customer.</p>
<h2>7. Confidentiality</h2><p>7.1 Each party shall keep the other's Confidential Information confidential for five (5) years after termination and shall use it only to perform this Agreement.</p>
<h2>8. Liability</h2><p>8.1 Neither party is liable for indirect or consequential loss, loss of profit or loss of goodwill.</p><p>8.2 {cap}</p><p>8.3 Nothing in this Agreement limits liability for death or personal injury caused by negligence, for fraud, or for any liability that cannot be limited by law.</p>
<h2>9. Termination</h2><p>9.1 Either party may terminate this Agreement on thirty (30) days' written notice if the other commits a material breach that is not remedied within that period. Notice under this clause 9 is separate from notice of non-renewal under clause 3.</p>
<h2>10. General</h2><p>10.1 Notices shall be in writing and delivered by hand or recorded post. A notice is deemed received two (2) business days after posting.</p>
<h2>11. Governing law and jurisdiction</h2><p>11.1 This Agreement and any dispute arising from it shall be governed by the laws of {e(r['law'])}.</p><p>11.2 The parties submit to the exclusive jurisdiction of {e(r['venue'])}.</p>
{amend}
<table style='margin-top:26px'><tr>
<td style='width:48%;vertical-align:top'><b>Signed for {e(r['prov'])}</b><br><br>______________________<br>Name: A. Whitcombe<br>Title: Director<br>Date: {long(r['sig1'])}</td><td style='width:4%'></td>
<td style='vertical-align:top'><b>Signed for {e(r['cust'])}</b><br><br>______________________<br>Name: R. Okonjo<br>Title: Head of Procurement<br>Date: {long(r['sig2'])}</td></tr></table>
</div>"""
    return f"<html><head><meta charset='utf-8'><style>{CSS} body{{font-size:10.2pt}}</style></head><body>{body}</body></html>"

# ---------------------------------------------------------------- render
def chromium():
    c = sorted(glob.glob(os.path.expanduser('~/.cache/ms-playwright/chromium_headless_shell-*/chrome-*/headless_shell')) +
               glob.glob(os.path.expanduser('~/.cache/ms-playwright/chromium-*/chrome-linux*/chrome')))
    if not c: sys.exit('no chromium found under ~/.cache/ms-playwright')
    return c[0]

def to_pdf(html_text, pdf_path):
    hp = pdf_path[:-4] + '.html'
    open(hp, 'w', encoding='utf-8').write(html_text)
    subprocess.run([chromium(), '--headless', '--no-sandbox', '--disable-gpu', '--no-pdf-header-footer', f'--print-to-pdf={pdf_path}', 'file://' + hp],
                   check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    os.remove(hp)

def scan(pdf_path, rec):
    """Turn a digital PDF into an image-only 'scan': grey, slightly rotated, noisy, JPEG-compressed."""
    r = random.Random(SEED + hash(rec['id']) % 9973)
    doc = fitz.open(pdf_path); pages = []
    for page in doc:
        pix = page.get_pixmap(dpi=r.choice([110, 120, 130]))
        im = Image.frombytes('RGB', (pix.width, pix.height), pix.samples).convert('L')
        im = im.rotate(r.uniform(-1.6, 1.6), resample=Image.BICUBIC, expand=False, fillcolor=255)
        if r.random() < 0.5 and rec['kind'] == 'invoice':   # received / paid stamp, placed over the lower left, away from the totals
            st = Image.new('L', (330, 90), 255); d = ImageDraw.Draw(st)
            try: f = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 30)
            except Exception: f = ImageFont.load_default()
            d.rectangle([3, 3, 326, 86], outline=70, width=4); d.text((18, 26), r.choice(['RECEIVED', 'ENTERED', 'APPROVED']) + ' ' + r.choice(['AP', 'FIN']), fill=70, font=f)
            st = st.rotate(r.uniform(-14, 14), expand=True, fillcolor=255)
            im.paste(Image.composite(st, im.crop((40, im.height - 330, 40 + st.width, im.height - 330 + st.height)), st.point(lambda p: 255 if p < 200 else 0)), (40, im.height - 330))
        a = np.asarray(im).astype(np.float32)
        a += np.random.default_rng(SEED + len(pages)).normal(0, r.uniform(5, 11), a.shape)
        a = a * r.uniform(0.9, 0.97) + r.uniform(4, 14)
        im = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(r.uniform(0.35, 0.8)))
        buf = io.BytesIO(); im.save(buf, 'JPEG', quality=r.choice([38, 45, 55])); pages.append(buf.getvalue())
    doc.close()
    out = fitz.open()
    for jpg in pages:
        img = fitz.open(stream=jpg, filetype='jpg'); rect = img[0].rect
        p = out.new_page(width=595, height=842); p.insert_image(fitz.Rect(0, 0, 595, 842), stream=jpg)
    out.save(pdf_path, deflate=True); out.close()

def main():
    os.makedirs(OUT, exist_ok=True)
    for f in glob.glob(os.path.join(OUT, '*')): os.remove(f)
    recs = []
    for i in range(1, 16): recs.append(make_invoice(i, 'clean'))
    for i in range(16, 31): recs.append(make_invoice(i, 'scan'))
    for k, trap in enumerate(TRAPS): recs.append(make_invoice(31 + k, 'trap', trap))
    for i in range(1, 6): recs.append(make_contract(i, 'clean'))
    for k, trap in enumerate(CTRAPS): recs.append(make_contract(6 + k, 'scan' if k >= 5 else 'trap', trap))
    key, rows = {}, []
    for rec in recs:
        pdf = os.path.join(OUT, rec['id'] + '.pdf')
        to_pdf(invoice_html(rec) if rec['kind'] == 'invoice' else contract_html(rec), pdf)
        scanned = rec['tier'] == 'scan'
        if scanned: scan(pdf, rec)
        pages = fitz.open(pdf).page_count
        key[rec['id']] = dict(kind=rec['kind'], tier=rec['tier'], trap=rec['trap'], scanned=scanned, language=rec['lang'], pages=pages, truth=rec['truth'])
        rows.append([rec['id'], rec['kind'], rec['tier'], rec['trap'], 'yes' if scanned else 'no', rec['lang'], pages])
        print(rec['id'], rec['tier'], rec['trap'], pages)
    json.dump(key, open(os.path.join(HERE, 'answer-key.json'), 'w'), indent=1, ensure_ascii=False)
    with open(os.path.join(HERE, 'manifest.csv'), 'w', newline='') as f:
        w = csv.writer(f); w.writerow(['id', 'kind', 'tier', 'trap', 'scanned', 'language', 'pages']); w.writerows(rows)

if __name__ == '__main__':
    main()
