"""
A judge-substitution study
==========================

Before an AI judge replaces people in a session, the same queries should be
answered by both, and four questions answered: How often do they agree? How
often is each right (where a ground truth exists)? Does the AI's reported
uncertainty predict its errors — the property hybrid escalation relies on?
What does each answer cost? :func:`~easyiec.validation.compare_evaluators`
runs such a study.
"""

# %%
# Segmentation quality with a ground truth
# ----------------------------------------
# :class:`~easyiec.problems.ImageSegmentation` knows the true cell mask, so the
# Dice coefficient is an objective oracle. The panel asks a careful and a
# hurried simulated person, two mock AI judges and a three-persona panel.
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.evaluators import LLMJudge, MockJudgeClient, Panel
from easyiec.problems import ImageSegmentation
from easyiec.validation import compare_evaluators

problem = ImageSegmentation()
dice = problem.utility
evaluators = {
    "careful person": ei.SimulatedUser(problem, target="default", noise=0.03, seed=1),
    "hurried person": ei.SimulatedUser(problem, target="default", noise=0.12, lapse=0.1, seed=2),
    "good AI": LLMJudge(MockJudgeClient(dice, score_on="genome", noise=0.05, seed=3), problem, image_size=48),
    "weak AI": LLMJudge(MockJudgeClient(dice, score_on="genome", noise=0.2, seed=4), problem, image_size=48),
    "AI panel (3)": Panel([LLMJudge(MockJudgeClient(dice, score_on="genome", noise=0.2, seed=10 + k), problem,
                                    image_size=48) for k in range(3)]),
}
study = compare_evaluators(problem, evaluators, n_queries=40, kind="pairs", n_items=4, reference="careful person",
                           oracle=dice, seed=0)
print(study.table().round(3).to_string(index=False))
# %%
# Agreement between evaluators
# ----------------------------
ei.viz.plot_agreement(study.agreement, title="share of duels decided alike")

# %%
# Accuracy and the value of uncertainty
# -------------------------------------
# AUROC of 0.5 means the reported uncertainty says nothing about errors; the
# debiased AI judges flag their own uncertain duels, which is what makes
# escalation to a person efficient.
tab = study.table().set_index("evaluator")
fig, axes = plt.subplots(1, 2, figsize=(10, 3))
axes[0].barh(tab.index, tab["oracle_accuracy"], color="#285780")
axes[0].set_xlim(0.5, 1)
axes[0].set_title("agreement with the Dice oracle", fontsize=9)
if "uncertainty_auroc" in tab:
    au = tab["uncertainty_auroc"].dropna()
    axes[1].barh(au.index, au, color="#D55E00")
    axes[1].axvline(0.5, color="0.5", ls="--", lw=0.8)
    axes[1].set_xlim(0, 1)
    axes[1].set_title("AUROC of uncertainty for predicting errors", fontsize=9)
fig.tight_layout()
plt.show()
