"""File a research paper under its subject area.

The papers are real: submitted to arXiv in 2026, each with the primary subject area its authors chose. Run it with
`pip install openai`, then `python classify-research-papers.py`. The API is free and needs no key.
"""
# === setup ===
import json
import math
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 classify(question, text, labels, heading="Text", descriptions=None, allow_none=False):
    """(label, confidence)"""
    options = "\n".join(f"- {label}: {descriptions[label]}" if descriptions else f"- {label}" for label in labels)
    prompt = f"{question}\n\n{heading}:\n{text}\n\nOptions:\n{options}\n\nAnswer with the label only."
    if allow_none:
        prompt += ' If none of the options fits, answer "none".'
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "user", "content": prompt}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=24,
        logprobs=True,                      # for the confidence
        extra_body={"structured_outputs": {"choice": labels + (["none"] if allow_none else [])}},
    )
    choice = reply.choices[0]
    tokens = [t for t in choice.logprobs.content if not t.token.startswith("<|")]
    confidence = math.exp(sum(t.logprob for t in tokens))
    return choice.message.content, confidence

# === the data ===
DATA = json.loads((Path(__file__).parent / "data" / "classify-research-papers.json").read_text())
QUESTION = DATA["question"]
AREAS = DATA["labels"]                      # arXiv's eight subject areas
ABOUT = DATA["descriptions"]                # a few words on what each one covers


def text_of(paper):
    """The title, then the abstract under a heading of its own. Sent with heading="Title", this is the layout the
    model was trained on, with two blocks of text in place of one."""
    return f"{paper['title']}\n\nAbstract:\n{paper['text']}"


print(QUESTION)
for name in AREAS:
    print(f"- {name}: {ABOUT[name]}")

# === the request ===
paper = DATA["examples"][0]
print(paper["title"])
print(textwrap.fill(paper["text"][:420] + " [...]", 100))

label, confidence = classify(QUESTION, text_of(paper), AREAS, heading="Title", descriptions=ABOUT)
print()
print(f"model:   {label} ({confidence:.0%} sure)")
print(f"authors: {paper['label']}")

# === six papers ===
for paper in DATA["examples"]:
    label, confidence = classify(QUESTION, text_of(paper), AREAS, heading="Title", descriptions=ABOUT)
    print(f"{label:<44} {confidence:4.0%}   {paper['title'][:50]}")

# === check every label ===
sample = DATA["sample"]                     # 60 papers, taken without looking at the answers
answers = [classify(QUESTION, text_of(paper), AREAS, heading="Title", descriptions=ABOUT)[0] for paper in sample]

right = sum(label == paper["label"] for label, paper in zip(answers, sample))
print(f"{right} of {len(sample)} right ({right / len(sample):.0%})")
print()
for area in AREAS:
    said = [label for label, paper in zip(answers, sample) if paper["label"] == area]
    print(f"{area:<44} {sum(label == area for label in said):2d} of {len(said):2d}")
