#!/usr/bin/env python3
"""
Lynx Helse evaluation: open Nordic medical multiple-choice tests, run through an
OpenAI-compatible chat API.

Every benchmark is downloaded from its public source on Hugging Face when the script
runs; no questions are bundled here. Each question is sent as one chat message with
lettered options, and the model's first answer letter is scored against the key.

    pip install openai datasets
    export BINERIC_API_KEY=api_...
    python lynx_helse_eval.py                        # every benchmark
    python lynx_helse_eval.py --benchmarks sv-physician-exam --limit 50

Any OpenAI-compatible endpoint and model can be tested the same way:

    python lynx_helse_eval.py --base-url https://api.bineric.com/v1 --model claude-opus-5.5

Licences differ per dataset (see BENCHMARKS below). The Swedish physician exam and
NorMedQA have no clear licence: use them for evaluation only, and do not republish them.
"""

import argparse
import ast
import hashlib
import json
import os
import random
import re
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from datetime import datetime, timezone

LETTERS = "ABCDEFGHIJ"

# MMLU subjects that are about medicine and the body.
MEDICAL_SUBJECTS = {
    "anatomy",
    "clinical_knowledge",
    "college_biology",
    "college_medicine",
    "high_school_biology",
    "human_aging",
    "human_sexuality",
    "medical_genetics",
    "nutrition",
    "professional_medicine",
    "virology",
}

# "Answer with the letter only", per language.
INSTRUCTIONS = {
    "nb": "Svar kun med bokstaven for det riktige alternativet.",
    "sv": "Svara endast med bokstaven för det rätta alternativet.",
    "da": "Svar kun med bogstavet for den rigtige mulighed.",
    "fi": "Vastaa vain oikean vaihtoehdon kirjaimella.",
    "is": "Svaraðu aðeins með bókstaf rétta svarsins.",
}


@dataclass
class Item:
    id: str
    question: str
    choices: list
    gold: int  # index into choices


def _stable_shuffle(key, options):
    """The same order on every run and machine, so results can be reproduced."""
    seed = int(hashlib.sha256(key.encode("utf-8")).hexdigest()[:16], 16)
    order = list(range(len(options)))
    random.Random(seed).shuffle(order)
    return order


def load_normedqa():
    from datasets import load_dataset

    rows = load_dataset("SimulaMet/NorMedQA", split="train")
    seen, items = set(), []
    for i, r in enumerate(rows):
        question = (r["question"] or "").strip()
        wrong = r["wrong_answers"]
        # Stored as one string, "option one; option two; option three".
        if isinstance(wrong, str):
            text = wrong.strip()
            if text.startswith("["):
                try:
                    wrong = ast.literal_eval(text)
                except (ValueError, SyntaxError):
                    wrong = [text]
            else:
                wrong = text.split(";")
        options = [str(r["answer"]).strip()] + [str(w).strip() for w in (wrong or []) if str(w).strip()]
        key = re.sub(r"\s+", " ", question.lower())
        # The dataset repeats some questions; score each one once. Some rows lost their
        # wrong answers in conversion (one left, or several run together), so a question
        # needs at least three options to count.
        if not question or len(options) < 3 or key in seen:
            continue
        seen.add(key)
        order = _stable_shuffle(key, options)
        choices = [options[j] for j in order][: len(LETTERS)]
        if 0 not in order[: len(LETTERS)]:
            continue
        items.append(Item(f"normedqa/{i}", question, choices, order.index(0)))
    return items


def load_m_mmlu(lang):
    from datasets import load_dataset

    rows = load_dataset("alexandrainst/m_mmlu", lang, split="test")
    items = []
    for r in rows:
        subject = str(r["id"]).split("/")[0]
        if subject not in MEDICAL_SUBJECTS:
            continue
        choices = [r["option_a"], r["option_b"], r["option_c"], r["option_d"]]
        items.append(Item(str(r["id"]), r["instruction"], choices, LETTERS.index(str(r["answer"]).strip())))
    return items


def load_global_mmlu(lang):
    from datasets import load_dataset

    rows = load_dataset("CohereLabs/Global-MMLU", lang, split="test")
    items = []
    for r in rows:
        if r["subject"] not in MEDICAL_SUBJECTS:
            continue
        choices = [r["option_a"], r["option_b"], r["option_c"], r["option_d"]]
        items.append(Item(str(r["sample_id"]), r["question"], choices, LETTERS.index(str(r["answer"]).strip())))
    return items


def load_swedish_physician_exam():
    from datasets import load_dataset

    rows = load_dataset("sarafuyu/swedish-medical-exams-mcq-1006-json", split="train")
    items = []
    for i, r in enumerate(rows):
        options = r["options"]
        if isinstance(options, str):
            options = ast.literal_eval(options)
        choices = [str(o) for o in options][: len(LETTERS)]
        try:
            gold = int(str(r["answer"]).strip()) - 1  # the key is 1-based
        except ValueError:
            continue
        if 0 <= gold < len(choices) and len(choices) >= 2:
            items.append(Item(f"swedish-exam/{i}", r["question"], choices, gold))
    return items


def load_include_finnish_health():
    from datasets import load_dataset

    rows = load_dataset("CohereLabs/include-base-44", "Finnish", split="test")
    items = []
    for i, r in enumerate(rows):
        if "health" not in str(r["domain"]).lower():
            continue
        choices = [r["option_a"], r["option_b"], r["option_c"], r["option_d"]]
        answer = r["answer"]
        gold = int(answer) if str(answer).isdigit() else LETTERS.index(str(answer).strip())
        items.append(Item(f"include-fi/{i}", r["question"], choices, gold))
    return items


BENCHMARKS = {
    # name: (language, description, loader, licence note)
    "no-normedqa": ("nb", "NorMedQA, Norwegian medical questions", load_normedqa, "licence unclear: evaluation only"),
    "no-mmlu-medical": ("nb", "MMLU medical subjects, Norwegian", lambda: load_m_mmlu("nb"), "Okapi m_MMLU, CC BY-NC 4.0"),
    "sv-physician-exam": (
        "sv",
        "Swedish physician knowledge test (kunskapsprov för läkare)",
        load_swedish_physician_exam,
        "licence unknown: evaluation only",
    ),
    "sv-mmlu-medical": ("sv", "Global-MMLU medical subjects, Swedish", lambda: load_global_mmlu("sv"), "Apache 2.0"),
    "da-mmlu-medical": ("da", "MMLU medical subjects, Danish", lambda: load_m_mmlu("da"), "Okapi m_MMLU, CC BY-NC 4.0"),
    "fi-include-health": ("fi", "INCLUDE Finnish, health education exams", load_include_finnish_health, "Apache 2.0"),
    "is-mmlu-medical": ("is", "MMLU medical subjects, Icelandic", lambda: load_m_mmlu("is"), "Okapi m_MMLU, CC BY-NC 4.0"),
}


def build_prompt(item, lang):
    letters = LETTERS[: len(item.choices)]
    options = "\n".join(f"{letters[i]}. {c}" for i, c in enumerate(item.choices))
    return f"{item.question.strip()}\n\n{options}\n\n{INSTRUCTIONS[lang]}"


def parse_letter(text, n_choices):
    """The first answer letter in the reply, or None."""
    allowed = LETTERS[:n_choices]
    match = re.search(rf"(?<![A-Za-zÀ-ÿ])([{allowed}])(?![A-Za-zÀ-ÿ])", (text or "").strip())
    return allowed.index(match.group(1)) if match else None


def ask(client, model, prompt, max_tokens, retries=6):
    delay = 2.0
    for attempt in range(retries):
        try:
            reply = client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                temperature=0,
                max_tokens=max_tokens,
            )
            return reply.choices[0].message.content or ""
        except Exception as error:  # rate limits, timeouts, a server that is starting
            if attempt == retries - 1:
                print(f"  giving up on one question: {error}", file=sys.stderr)
                return None
            time.sleep(delay)
            delay = min(delay * 2, 60)


def run_benchmark(client, args, name):
    lang, description, loader, licence = BENCHMARKS[name]
    items = loader()
    if args.limit:
        items = items[: args.limit]
    print(f"\n{name}: {description} ({len(items)} questions)")

    results = [None] * len(items)
    with ThreadPoolExecutor(max_workers=args.workers) as pool:
        futures = {
            pool.submit(ask, client, args.model, build_prompt(item, lang), args.max_tokens): i
            for i, item in enumerate(items)
        }
        for done, future in enumerate(as_completed(futures), 1):
            i = futures[future]
            reply = future.result()
            pred = parse_letter(reply, len(items[i].choices)) if reply is not None else None
            results[i] = {"id": items[i].id, "pred": pred, "gold": items[i].gold, "failed": reply is None}
            if done % 100 == 0 or done == len(items):
                print(f"  {done}/{len(items)}", flush=True)

    answered = [r for r in results if not r["failed"]]
    correct = sum(1 for r in answered if r["pred"] == r["gold"])
    return {
        "benchmark": name,
        "language": lang,
        "description": description,
        "licence": licence,
        "questions": len(items),
        "answered": len(answered),
        "unparsed": sum(1 for r in answered if r["pred"] is None),
        "correct": correct,
        # Unparsed replies count as wrong; questions the API never answered are left out.
        "accuracy": round(100 * correct / len(answered), 1) if answered else None,
        "predictions": results if args.save_predictions else None,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--base-url", default=os.environ.get("BINERIC_BASE_URL", "https://api.bineric.com/v1"))
    parser.add_argument("--api-key", default=os.environ.get("BINERIC_API_KEY"))
    parser.add_argument("--model", default="bineric-lynx-helse")
    parser.add_argument("--benchmarks", nargs="+", choices=list(BENCHMARKS), default=list(BENCHMARKS))
    parser.add_argument("--limit", type=int, default=0, help="first N questions per benchmark (0 = all)")
    parser.add_argument("--workers", type=int, default=4, help="requests in flight at once")
    parser.add_argument(
        "--max-tokens", type=int, default=1024, help="room for models that reason before answering; others stop after one letter"
    )
    parser.add_argument("--out", default="lynx_helse_eval_results.json")
    parser.add_argument("--save-predictions", action="store_true", help="keep each answer letter in the output")
    args = parser.parse_args()

    if not args.api_key:
        sys.exit("Set BINERIC_API_KEY or pass --api-key.")

    from openai import OpenAI

    client = OpenAI(base_url=args.base_url, api_key=args.api_key, timeout=120)
    started = datetime.now(timezone.utc)
    print(f"Model {args.model} at {args.base_url}")

    scores = [run_benchmark(client, args, name) for name in args.benchmarks]

    print(f"\n{'benchmark':<20} {'lang':<5} {'n':>6} {'accuracy':>9}")
    for s in scores:
        acc = f"{s['accuracy']:.1f}" if s["accuracy"] is not None else "-"
        print(f"{s['benchmark']:<20} {s['language']:<5} {s['answered']:>6} {acc:>9}")

    with open(args.out, "w", encoding="utf-8") as f:
        json.dump(
            {
                "model": args.model,
                "base_url": args.base_url,
                "started": started.isoformat(),
                "finished": datetime.now(timezone.utc).isoformat(),
                "settings": {"temperature": 0, "max_tokens": args.max_tokens, "limit": args.limit},
                "scores": scores,
            },
            f,
            ensure_ascii=False,
            indent=2,
        )
    print(f"\nSaved {args.out}")


if __name__ == "__main__":
    main()
