#!/usr/bin/env python3
"""ODIN open tier (T0) — reproduce the CDSS baseline from published weights.

Usage:
    pip install scikit-learn==1.6.1 pandas numpy
    python3 baseline.py model-v0.pkl synthetic-dental-implants-v0.csv

Prints per-model AUROC of the published ensemble on the CC0 synthetic cohort.
HONESTY NOTE: the synthetic dataset mirrors marginal distributions of the real
training cohort (n=747, Taiwan, doi:10.5281/zenodo.1227714) but NOT its joint
structure - use it to validate pipelines and I/O, not to benchmark accuracy.
The frozen real-test AUROC of these weights is 0.8213 (see the model card).
sklearn MUST be 1.6.1: the pickle does not load on 1.9+ (_RemainderColsList).
"""
import pickle
import sys

import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score

pkl_path = sys.argv[1] if len(sys.argv) > 1 else "model-v0.pkl"
csv_path = sys.argv[2] if len(sys.argv) > 2 else "synthetic-dental-implants-v0.csv"

with open(pkl_path, "rb") as f:
    bundle = pickle.load(f)
model, feats = bundle["model"], bundle["features"]
print("bundle:", bundle.get("winner", "?"), "| features:", len(feats))

df = pd.read_csv(csv_path)
X = pd.DataFrame(index=df.index)
for k in feats:
    if k == "implant_volume":
        X[k] = df["implant_length_mm"] * df["implant_diameter_mm"] ** 2
    elif k == "len_x_diam":
        X[k] = df["implant_length_mm"] * df["implant_diameter_mm"]
    elif k in df.columns:
        X[k] = df[k]
    else:
        X[k] = np.nan  # honestly absent in the synthetic release (anonymised codes etc.)

y = df["unfavorable_outcome"].astype(int)
# uncalibrated ensemble score - the same quantity the live CDSS turns into percentiles
score = np.mean([cc.estimator.predict_proba(X)[:, 1] for cc in model.calibrated_classifiers_], axis=0)
print(f"synthetic n={len(df)}, events={int(y.sum())} ({y.mean():.1%})")
print(f"AUROC on synthetic cohort: {roc_auc_score(y, score):.4f}")
print("Expected: below the 0.8213 real-test AUROC — synthetic joints are simplified.")