"""Send a question to the community that can answer it.

The questions are real: asked on ten Stack Exchange sites in 2026 (CC BY-SA 4.0; every question keeps its author and
its link), each with the site it was asked on. Run it with `pip install openai`, then
`python classify-forum-questions.py`. The API is free and needs no key.
"""
# === setup ===
import json
import math
import textwrap
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 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-forum-questions.json").read_text())
QUESTION = DATA["question"]
COMMUNITIES = DATA["labels"]                # ten communities


def text_of(post):
    """The title, then the body of the question under a heading of its own."""
    return f"{post['title']}\n\nQuestion:\n{post['text']}"


print(QUESTION)
for name in COMMUNITIES:
    print(f"- {name}")

# === the request ===
post = DATA["examples"][0]
print(post["title"])
print(textwrap.fill(post["text"], 100))
print(f"(asked by {post['author']}: {post['url']})")

label, confidence = classify(QUESTION, text_of(post), COMMUNITIES, heading="Title")
print()
print(f"model:    {label} ({confidence:.0%} sure)")
print(f"asked on: {post['label']}")

# === six questions ===
for post in DATA["examples"]:
    label, confidence = classify(QUESTION, text_of(post), COMMUNITIES, heading="Title")
    print(f"{label:<38} {confidence:4.0%}   {post['title'][:54]} ({post['author']})")

# === many at once ===
sample = DATA["sample"]                     # 60 questions, taken without looking at the answers
start = time.perf_counter()
with ThreadPoolExecutor(16) as pool:        # 16 requests in flight at a time
    answers = list(pool.map(lambda post: classify(QUESTION, text_of(post), COMMUNITIES, heading="Title"), sample))
seconds = time.perf_counter() - start
print(f"{len(sample)} questions in {seconds:.1f} s: {len(sample) / seconds:.0f} a second")

# === measure it ===
for threshold in (0.0, 0.8, 0.9, 0.95):
    kept = [(label, post) for (label, confidence), post in zip(answers, sample) if confidence >= threshold]
    right = sum(label == post["label"] for label, post in kept)
    print(f"confidence at least {threshold:.2f}: {len(kept):2d} of {len(sample)} kept, {right:2d} right ({right / len(kept):.0%})")
