"""Is my quantum classifier's confidence reliable?

Worked example from https://www.ozgurcatak.net/quantumuq.html
Requires: pip install quantumuq pennylane   (tested with QuantumUQ 0.4.1, PennyLane 0.45.1, Python 3.12)
"""
import numpy as np
from quantumuq import wrap_qnode, ShotBootstrap, ece, brier, nll
from quantumuq.benchmarks.datasets import load_moons
from quantumuq.benchmarks.models import train_pennylane_vqc

# 1. Data: two-moons (200 points), subsample 150, 70/30 train/test split, fixed seed
data = load_moons(random_state=0)
rng = np.random.default_rng(0)
keep = rng.choice(len(data.X), 150, replace=False)
X, y = data.X[keep], data.y[keep]
perm = rng.permutation(len(X))
test, train = perm[:45], perm[45:]

# 2. Train QuantumUQ's reference variational classifier (2 qubits, 2 layers) in PennyLane
qnode, params, postprocess = train_pennylane_vqc(X[train], y[train], seed=0)
predictor = wrap_qnode(qnode, task="classification", n_classes=2,
                       params=params, postprocess=postprocess)

# Cross-entropy cannot tell the two class labels apart, so training may converge
# with them swapped. Detect that once on the training set (as run_benchmark does).
p_train = predictor.with_uq(ShotBootstrap(n_samples=1, shots=1000, seed=0)).predict_dist(X[train]).mean
swap = (p_train.argmax(1) == y[train]).mean() < 0.5

# 3. Re-measure the same trained model at three shot budgets
print(f"{'shots':>6} {'accuracy':>9} {'mean conf':>9} {'ECE':>6} {'Brier':>6} {'NLL':>6} {'shot std':>9}")
for shots in (100, 1_000, 10_000):
    dist = predictor.with_uq(ShotBootstrap(n_samples=8, shots=shots, seed=0)).predict_dist(X[test])
    p = dist.mean[:, ::-1] if swap else dist.mean
    acc = (p.argmax(1) == y[test]).mean()
    print(f"{shots:>6} {acc:>9.2f} {p.max(1).mean():>9.2f} {ece(y[test], p):>6.3f} "
          f"{brier(y[test], p):>6.3f} {nll(y[test], p):>6.3f} {dist.std.mean():>9.4f}")
