"""Pull the recalling firm and the quantity out of a recall notice.

The notices are real: recalls of food, drugs and medical devices that the US Food and Drug Administration published
in 2026 (openFDA), each with the values of FDA's own record. Run it with `pip install openai`, then
`python extract-recall-notices.py`. The API is free and needs no key.
"""
# === setup ===
import json
import re
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")

# === the recipe ===
def extract(kind, document, fields, max_tokens=800):
    """{field: value or None}. fields: [{"name", "type", "description"}], plus "schema" for lists and objects."""
    lines = "\n".join(f"- {f['name']} ({f['type']}): {f['description']}" for f in fields)
    system = (f"You extract structured data from {kind}s. For each document the user sends, give these fields.\n\n"
              f"Fields:\n{lines}\n\n"
              "Answer with one JSON object with exactly these keys. Use null for a field the text does not give.")
    properties = {f["name"]: f.get("schema") or {"type": [f["type"], "null"]} for f in fields}
    schema = {"type": "object", "properties": properties, "required": [f["name"] for f in fields],
              "additionalProperties": False}
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "system", "content": system}, {"role": "user", "content": document}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=max_tokens,
        response_format={"type": "json_schema", "json_schema": {"name": "record", "schema": schema}},
    )
    choice = reply.choices[0]
    if choice.finish_reason != "stop":      # "length": the JSON was cut off and will not parse
        raise RuntimeError(f"the reply was cut off ({choice.finish_reason}): raise max_tokens")
    return json.loads(choice.message.content)

# === the data ===
DATA = json.loads((Path(__file__).parent / "data" / "extract-recall-notices.json").read_text())
KIND = DATA["kind"]                         # "product recall report"
FIELDS = DATA["fields"]

for field in FIELDS:
    print(f"- {field['name']} ({field['type']}): {field['description']}")

# === the request ===
notice = DATA["examples"][0]
print(notice["document"])

record = extract(KIND, notice["document"], FIELDS)
print()
print(json.dumps(record, indent=2))

# === check it ===
def same(value, answer):
    """Is an extracted value the right one? Text is compared by its letters and digits (case, spaces and
    punctuation aside), numbers as numbers, and a field the document does not state has to be null."""
    if value is None or answer is None:
        return value is None and answer is None
    if isinstance(answer, (int, float)):
        return isinstance(value, (int, float)) and value == answer
    squeeze = lambda s: "".join(c for c in str(s).casefold() if c.isalnum())      # noqa: E731
    return squeeze(value) == squeeze(answer)


for name, value in record.items():
    verdict = "right" if same(value, notice["answer"][name]) else f"WRONG, FDA has {notice['answer'][name]!r}"
    print(f"{name:<19} {value!r:<13} {verdict}")

# === every notice, eight at a time ===
notices = DATA["sample"]                    # every notice the test set has an answer for on all five fields
start = time.perf_counter()
with ThreadPoolExecutor(8) as pool:
    records = list(pool.map(lambda notice: extract(KIND, notice["document"], FIELDS), notices))
seconds = time.perf_counter() - start

for notice, record in zip(notices, records):
    ok = all(same(record[name], notice["answer"][name]) for name in record)
    where = f"{record['firm_city']}, {record['firm_state']} {record['firm_zip_code']}"
    print(f"{notice['id'][8:]:<12} {where:<28} {record['quantity']:>9,}  {record['fda_classification']}  "
          f"{'right' if ok else 'WRONG: ' + json.dumps(notice['answer'])}")
print(f"{len(notices)} notices in {seconds:.1f} s")

# === validate before you store ===
def problems(record):
    """What is wrong with a record by rules that need no model. An empty list: store it."""
    found = []
    if not re.fullmatch(r"\d{5}", record["firm_zip_code"] or ""):
        found.append("the ZIP code is not five digits")
    if not re.fullmatch(r"[A-Z]{2}", record["firm_state"] or ""):
        found.append("the state is not a two-letter code")
    if not isinstance(record["quantity"], int) or record["quantity"] <= 0:
        found.append("the quantity is not a positive whole number")
    if record["fda_classification"] not in (None, "Class I", "Class II", "Class III"):
        found.append("the classification is not one FDA uses")
    return found


stored = [record for record in records if not problems(record)]
print(f"{len(stored)} of {len(records)} records pass every rule")

# === measure it ===
right = {field["name"]: 0 for field in FIELDS}
complete = 0
for notice, record in zip(notices, records):
    ok = {name: same(record[name], notice["answer"][name]) for name in right}
    complete += all(ok.values())
    for name in right:
        right[name] += ok[name]

print(f"{complete} of {len(notices)} notices with every field right")
for name, n in right.items():
    print(f"{name:<19} {n} of {len(notices)}")
