#!/usr/bin/env python3
"""Run the document-extraction test: every PDF in docs/ through each model, once per run.

Same prompt and same JSON schema for every model; each vendor's own structured-output
feature is used so a malformed reply is the model's fault, not the harness's.

Usage:  venv/bin/python run.py --run 1 [--models a,b] [--only inv-01,con-02] [--workers 4]
Keys:   OPENAI_API_KEY, GEMINI_API_KEY, ANTHROPIC_API_KEY in the environment.
Output: results/run<N>/<model>/<doc>.json  (raw reply, parsed JSON, token usage, latency)
"""
import argparse, base64, concurrent.futures as cf, json, os, sys, time

HERE = os.path.dirname(os.path.abspath(__file__))
MODELS = {
    'gpt-6.2-sol': 'openai', 'gpt-6-luna': 'openai',
    'gemini-4-hydrogen': 'google', 'gemini-3.5-flash-lite': 'google',
    'claude-sonnet-5-5': 'anthropic', 'claude-haiku-5-5': 'anthropic',
}

def nullable(t): return {'type': [t, 'null']}
INVOICE_SCHEMA = {'type': 'object', 'additionalProperties': False, 'properties': {
    'vendor_name': {'type': 'string'}, 'invoice_number': {'type': 'string'}, 'invoice_date': {'type': 'string'}, 'due_date': nullable('string'),
    'currency': {'type': 'string'}, 'subtotal': {'type': 'number'}, 'tax_total': {'type': 'number'}, 'total': {'type': 'number'},
    'po_number': nullable('string'), 'document_type': {'type': 'string', 'enum': ['invoice', 'credit_note']}, 'line_item_count': {'type': 'integer'}},
    'required': ['vendor_name', 'invoice_number', 'invoice_date', 'due_date', 'currency', 'subtotal', 'tax_total', 'total', 'po_number', 'document_type', 'line_item_count']}
CONTRACT_SCHEMA = {'type': 'object', 'additionalProperties': False, 'properties': {
    'provider_name': {'type': 'string'}, 'customer_name': {'type': 'string'}, 'effective_date': {'type': 'string'}, 'initial_term_months': {'type': 'integer'},
    'auto_renews': {'type': 'boolean'}, 'renewal_notice_days': nullable('integer'), 'governing_law': {'type': 'string'}, 'payment_terms_days': {'type': 'integer'},
    'liability_cap_type': {'type': 'string', 'enum': ['fees_paid_12_months', 'fixed_amount', 'uncapped']}, 'liability_cap_amount': nullable('number')},
    'required': ['provider_name', 'customer_name', 'effective_date', 'initial_term_months', 'auto_renews', 'renewal_notice_days', 'governing_law', 'payment_terms_days', 'liability_cap_type', 'liability_cap_amount']}

INVOICE_PROMPT = """You are processing a supplier document for an accounts payable team. Extract these fields from the attached PDF and return JSON only.

- vendor_name: the legal name of the company that issued the document, exactly as printed (the registered entity, not just a logo or brand name).
- invoice_number: the document's own number (for a credit note, the credit note number). Not a customer account, quote or order number.
- invoice_date: the issue date as YYYY-MM-DD.
- due_date: the payment due date as YYYY-MM-DD. If no due date is printed but payment terms are (for example "Net 30"), calculate it from the invoice date. null only if neither is given.
- currency: the ISO 4217 code of the currency the document is billed in (for example USD, EUR, GBP).
- subtotal: the amount before tax, as a number.
- tax_total: the total tax (VAT, GST, sales tax) as a number. Add the lines together if several rates are shown.
- total: the document total including tax, before any deposits or payments already made are subtracted.
- po_number: the buyer's purchase order number, or null if the document does not give one.
- document_type: "invoice" or "credit_note".
- line_item_count: how many billed line items the document lists across all pages (do not count subtotal, discount, shipping or tax rows).

Numbers use a dot as the decimal separator and no thousands separator. For a credit note, return subtotal, tax_total and total as negative numbers."""

CONTRACT_PROMPT = """You are processing a signed services agreement for a contracts team. Extract these fields from the attached PDF and return JSON only.

- provider_name: the legal name of the party providing the services, as printed.
- customer_name: the legal name of the customer, as printed.
- effective_date: the date the agreement takes effect, as YYYY-MM-DD.
- initial_term_months: the length of the initial term in months, as it finally applies after any special terms or overrides in the document.
- auto_renews: true if the agreement renews automatically at the end of the initial term, otherwise false.
- renewal_notice_days: the number of days' notice needed to stop an automatic renewal, or null if the agreement does not renew automatically.
- governing_law: the jurisdiction whose law governs the agreement (not the court venue).
- payment_terms_days: the number of days the customer has to pay an invoice.
- liability_cap_type: "fees_paid_12_months" if liability is capped at fees paid or payable over twelve months, "fixed_amount" if it is capped at a stated sum, "uncapped" if there is no cap.
- liability_cap_amount: the stated sum as a number when liability_cap_type is "fixed_amount", otherwise null."""

# ---------------------------------------------------------------- set B (hard invoices with line items)
def obj(props): return {'type': 'object', 'additionalProperties': False, 'properties': props, 'required': list(props)}
S, N, I = {'type': 'string'}, {'type': 'number'}, {'type': 'integer'}
RENTAL_SCHEMA = obj({'vendor_name': S, 'invoice_number': S, 'invoice_date': S, 'rental_agreement_number': S, 'po_number': nullable('string'), 'job_number': nullable('string'),
    'billed_from': S, 'billed_through': S, 'invoice_type': {'type': 'string', 'enum': ['cycle_bill', 'final_return', 'credit']},
    'rental_subtotal': N, 'rental_protection_plan': N, 'environmental_charge': N, 'delivery_charge': N, 'pickup_charge': N, 'sales_items_total': N, 'tax_total': N, 'total': N,
    'lines': {'type': 'array', 'items': obj({'equipment_number': S, 'quantity': I, 'day_rate': N, 'week_rate': N, 'four_week_rate': N, 'amount': N})}})
PAINT_SCHEMA = obj({'vendor_name': S, 'invoice_number': S, 'invoice_date': S, 'account_number': S, 'po_number': nullable('string'),
    'subtotal': N, 'stewardship_fee_total': N, 'tax_total': N, 'total': N,
    'lines': {'type': 'array', 'items': obj({'sales_number': S, 'color_code': nullable('string'), 'quantity': I, 'unit': S, 'unit_price': N, 'amount': N})}})
SCREEN_SCHEMA = obj({'vendor_name': S, 'invoice_number': S, 'invoice_date': S, 'customer_account': S, 'po_number': nullable('string'), 'billing_period_start': S, 'billing_period_end': S,
    'services_subtotal': N, 'program_fee': N, 'credits_total': N, 'tax_total': N, 'total': N,
    'lines': {'type': 'array', 'items': obj({'service_code': S, 'quantity': I, 'unit_price': N, 'amount': N})},
    'locations': {'type': 'array', 'items': obj({'location_code': S, 'amount': N})}})
COMMON = " Dates are YYYY-MM-DD. Numbers use a dot as the decimal separator and no thousands separator. Use 0 for a charge the document does not have. Credits and returns are negative numbers."
RENTAL_PROMPT = """You are processing an equipment rental invoice for an accounts payable team. Extract these fields from the attached PDF and return JSON only.

Header: vendor_name (the legal name of the rental company), invoice_number, invoice_date, rental_agreement_number (the rental agreement or contract number), po_number, job_number (null if none), billed_from and billed_through (the billing period), invoice_type ("cycle_bill" for a recurring 4-week cycle bill, "final_return" for the invoice issued when equipment is returned, "credit" for a credit memo), rental_subtotal, rental_protection_plan, environmental_charge, delivery_charge, pickup_charge, sales_items_total (the subtotal of sales and miscellaneous items), tax_total, total.

lines: one entry for every rented equipment line on every page, in order. For each: equipment_number (the rental company's equipment or fleet number, not the serial number), quantity, day_rate, week_rate, four_week_rate (the rates printed for that line) and amount (what was actually billed for that line). Do not include sales or miscellaneous items in lines.""" + COMMON
PAINT_PROMPT = """You are processing a paint supplier invoice for an accounts payable team. Extract these fields from the attached PDF and return JSON only.

Header: vendor_name (the legal name of the supplier), invoice_number, invoice_date, account_number, po_number, subtotal (merchandise before fees and tax), stewardship_fee_total, tax_total, total.

lines: one entry for every product line, in order. For each: sales_number (the supplier's product or sales number), color_code (the colour code the product was tinted to, for example "AB 1234", or null for items with no colour), quantity, unit (the size or unit of measure as printed), unit_price (the price actually charged per unit, not the list price) and amount (the extended price).""" + COMMON
SCREEN_PROMPT = """You are processing an invoice from a workforce drug-testing and screening provider for an accounts payable team. Extract these fields from the attached PDF and return JSON only.

Header: vendor_name (the legal name of the provider), invoice_number, invoice_date, customer_account, po_number, billing_period_start and billing_period_end (the service period), services_subtotal, program_fee (a monthly program or administration fee), credits_total, tax_total, total.

lines: one entry per service code in the summary of charges: service_code, quantity, unit_price, amount.
locations: one entry per location in the charges by location: location_code, amount.""" + COMMON

def spec(doc_id):
    if doc_id.startswith('rent'): return RENTAL_PROMPT, RENTAL_SCHEMA
    if doc_id.startswith('paint'): return PAINT_PROMPT, PAINT_SCHEMA
    if doc_id.startswith('screen'): return SCREEN_PROMPT, SCREEN_SCHEMA
    return (INVOICE_PROMPT, INVOICE_SCHEMA) if doc_id.startswith('inv') else (CONTRACT_PROMPT, CONTRACT_SCHEMA)

DOCDIR = 'docs'

_clients = {}
def client(vendor):
    if vendor not in _clients:
        if vendor == 'openai':
            from openai import OpenAI; _clients[vendor] = OpenAI()
        elif vendor == 'google':
            from google import genai; _clients[vendor] = genai.Client(api_key=os.environ['GEMINI_API_KEY'])
        else:
            import anthropic; _clients[vendor] = anthropic.Anthropic()
    return _clients[vendor]

def call(model, doc_id, pdf):
    vendor = MODELS[model]; prompt, schema = spec(doc_id); c = client(vendor)
    b64 = base64.standard_b64encode(pdf).decode()
    if vendor == 'openai':
        r = c.responses.create(model=model, input=[{'role': 'user', 'content': [
            {'type': 'input_file', 'filename': doc_id + '.pdf', 'file_data': 'data:application/pdf;base64,' + b64},
            {'type': 'input_text', 'text': prompt}]}],
            text={'format': {'type': 'json_schema', 'name': 'extraction', 'schema': schema, 'strict': True}})
        u = r.usage
        return r.output_text, dict(input_tokens=u.input_tokens, output_tokens=u.output_tokens)
    if vendor == 'google':
        from google.genai import types
        r = c.models.generate_content(model=model, contents=[types.Part.from_bytes(data=pdf, mime_type='application/pdf'), prompt],
                                      config=types.GenerateContentConfig(response_mime_type='application/json', response_json_schema=schema))
        u = r.usage_metadata
        return r.text, dict(input_tokens=u.prompt_token_count or 0, output_tokens=(u.candidates_token_count or 0) + (u.thoughts_token_count or 0))
    r = c.messages.create(model=model, max_tokens=16000, messages=[{'role': 'user', 'content': [
        {'type': 'document', 'source': {'type': 'base64', 'media_type': 'application/pdf', 'data': b64}},
        {'type': 'text', 'text': prompt}]}],
        output_config={'format': {'type': 'json_schema', 'schema': schema}})
    text = ''.join(b.text for b in r.content if b.type == 'text')
    return text, dict(input_tokens=r.usage.input_tokens, output_tokens=r.usage.output_tokens)

def one(model, doc_id, outdir):
    path = os.path.join(outdir, model, doc_id + '.json')
    if os.path.exists(path) and not json.load(open(path)).get('error'): return 'skip'
    pdf = open(os.path.join(HERE, DOCDIR, doc_id + '.pdf'), 'rb').read()
    rec = dict(model=model, doc=doc_id, raw=None, parsed=None, usage=None, seconds=None, error=None)
    for attempt in range(3):   # retry transport / rate-limit errors only; a bad answer is never retried
        t = time.time()
        try:
            raw, usage = call(model, doc_id, pdf)
            rec.update(raw=raw, usage=usage, seconds=round(time.time() - t, 2), error=None)
            try: rec['parsed'] = json.loads(raw)
            except Exception as ex: rec['error'] = f'invalid JSON: {ex}'
            break
        except Exception as ex:
            rec['error'] = f'{type(ex).__name__}: {str(ex)[:300]}'; time.sleep(4 * (attempt + 1))
    os.makedirs(os.path.dirname(path), exist_ok=True)
    json.dump(rec, open(path, 'w'), indent=1, ensure_ascii=False)
    return 'err' if rec['error'] else 'ok'

def main():
    ap = argparse.ArgumentParser(); ap.add_argument('--run', default='1'); ap.add_argument('--models'); ap.add_argument('--only'); ap.add_argument('--workers', type=int, default=4); ap.add_argument('--set', default='a')
    a = ap.parse_args()
    models = a.models.split(',') if a.models else list(MODELS)
    global DOCDIR
    DOCDIR = 'docs' if a.set == 'a' else 'docs-' + a.set
    docs = sorted(f[:-4] for f in os.listdir(os.path.join(HERE, DOCDIR)) if f.endswith('.pdf'))
    if a.only: docs = [d for d in docs if d in a.only.split(',')]
    outdir = os.path.join(HERE, 'results' if a.set == 'a' else 'results-' + a.set, 'run' + a.run)
    for m in models:
        t = time.time()
        with cf.ThreadPoolExecutor(a.workers) as ex:
            res = list(ex.map(lambda d: one(m, d, outdir), docs))
        print(f'{m}: ok={res.count("ok")} err={res.count("err")} skipped={res.count("skip")} in {time.time()-t:.0f}s', flush=True)

if __name__ == '__main__':
    main()
