"""Log who an FDA warning letter went to, from which office and when.

The letters are real: warning letters the US Food and Drug Administration published in 2026, each with the values
of FDA's own listing of the letter. Run it with `pip install openai`, then `python extract-warning-letters.py`. The
API is free and needs no key.
"""
# === setup ===
import json
import re
import textwrap
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-warning-letters.json").read_text())
KIND = DATA["kind"]                         # "FDA warning letter"
FIELDS = DATA["fields"]

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

# === the request ===
letter = DATA["examples"][0]
print(textwrap.fill(letter["document"][:560], 100))
print(f"[... {len(letter['document']) - 560:,} more characters]")

record = extract(KIND, letter["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, letter["answer"][name]) else f"WRONG, FDA has {letter['answer'][name]!r}"
    print(f"{name:<18} {value!r:<30} {verdict}")

# === three letters ===
for letter in DATA["examples"]:
    record = extract(KIND, letter["document"], FIELDS)
    print(f"{record['letter_date']}  {record['issuing_office']:<40} {record['recipient_company']:<22} FEI {record['fei_number']}")

# === a letter about a website ===
def addressee(letter, record):
    """Who an FDA warning letter is addressed to. A letter about a website opens "To Whom It May Concern" and names
    no company, and the model then gives the FDA office that wrote it or another name in the letter. For those,
    take the website out of the text."""
    site = re.search(r"reviewed the (?:website )?https?://(?:www\.)?([\w.-]+)", letter)
    if "To Whom It May Concern" in letter and site:
        return site.group(1).rstrip(".")
    return record["recipient_company"]


for letter in DATA["website_letters"]:
    record = extract(KIND, letter["document"], FIELDS)
    opening = " ".join(letter["document"].split("To Whom It May Concern:")[1].split())
    print(textwrap.fill(opening[:205] + " [...]", 100))
    print(f"   the model:     {record['recipient_company']}")
    print(f"   with the rule: {addressee(letter['document'], record)}")
    print(f"   FDA lists it under: {letter['answer']['recipient_company']}")

# === measure it ===
sample = DATA["sample"]                     # every letter the test set has an answer for on all four fields
right = {field["name"]: 0 for field in FIELDS}
with_rule = 0
for letter in sample:
    record = extract(KIND, letter["document"], FIELDS)
    for name in right:
        right[name] += same(record[name], letter["answer"][name])
    with_rule += same(addressee(letter["document"], record), letter["answer"]["recipient_company"])

for name, n in right.items():
    print(f"{name:<34} {n} of {len(sample)}")
print(f"{'recipient_company, with the rule':<34} {with_rule} of {len(sample)}")
