"""
Hybrid evaluation: the AI answers, people decide the hard cases
===============================================================

An AI judge is cheap but sometimes wrong; a person is reliable but tires. The
:class:`~easyiec.evaluators.EscalationEvaluator` lets the AI answer and passes
a query to the person when the AI's uncertainty (disagreement of its views,
low stated confidence) exceeds a threshold τ. Three policies set τ: a fixed
value; a Robbins–Monro rule that holds a target share of human answers; and a
*risk-control* rule. The last one is calibrated, like split conformal methods
(Angelopoulos et al., 2024), on labels from a short calibration session in
which the person answered every query, keeps auditing a random fraction of the
AI's answers, and chooses the largest τ for which a Hoeffding upper bound on the
AI–person disagreement among non-escalated queries stays below a tolerance ε.
"""

# %%
# Three AI judges of different quality
# ------------------------------------
# The person is a careful simulated user; the mock AI judges share its taste
# but add judgment noise of 0.05, 0.1 or 0.2 on the utility scale. The strategy
# asks for eight pairwise duels per query (differential evolution).
import matplotlib.pyplot as plt
import numpy as np

import easyiec as ei
from easyiec.evaluators import EscalationEvaluator, LLMJudge, MockJudgeClient, disagreement
from easyiec.problems import ImageSegmentation
from easyiec.strategies import InteractiveDE

problem = ImageSegmentation()


def make(noise, seed):
    person = ei.SimulatedUser(problem, target="default", noise=0.03, seed=seed)
    ai = LLMJudge(MockJudgeClient(scorer=person.true_utility, score_on="genome", noise=noise, seed=seed + 1),
                  problem, image_size=32)
    return person, ai


rows, traces = [], {}
for noise in [0.05, 0.1, 0.2]:
    # calibration: the person answers every query of a short session
    person, ai = make(noise, 1)
    calib = EscalationEvaluator(ai, person, threshold=-1.0)
    ei.run(problem, InteractiveDE(pop_size=8), calib, generations=20, seed=11, oracle=person.true_utility)
    for policy in ["threshold", "rate", "risk"]:
        person, ai = make(noise, 5)
        hybrid = EscalationEvaluator(ai, person, policy=policy, threshold=0.3, target_rate=0.25,
                                     epsilon=0.3, delta=0.1, audit=0.1, calibration=calib.labels,
                                     granularity="decision", seed=3)
        res = ei.run(problem, InteractiveDE(pop_size=8), hybrid, generations=30, seed=4, oracle=person.true_utility)
        # realized error: an independent careful answer to every query the AI answered alone
        check = ei.SimulatedUser(problem, target="default", noise=0.03, seed=99)
        errs = [disagreement(r.query, r.feedback, check.evaluate(r.query)) for r in res.log.records
                if not r.feedback.escalated]
        rows.append((noise, policy, hybrid.summary()["human_rate"], np.mean(errs) if errs else np.nan))
        traces[(noise, policy)] = hybrid
for r in rows:
    print(f"AI noise {r[0]:.2f}  {r[1]:9s}  human share {r[2]:.2f}  AI-only disagreement {r[3]:.2f}")

# %%
# Human share and realized error
# ------------------------------
# A fixed threshold escalates according to the AI's *uncertainty*, whatever its
# real reliability; the rate rule holds its share regardless of quality. The
# risk-controlled policy asks the person rarely when the AI is good and almost
# always when it is not, keeping the disagreement of the AI-only answers near ε.
fig, axes = plt.subplots(1, 2, figsize=(10, 3.4))
policies = ["threshold", "rate", "risk"]
for k, pol in enumerate(policies):
    sub = [r for r in rows if r[1] == pol]
    x = np.arange(3) + (k - 1) * 0.26
    axes[0].bar(x, [r[2] for r in sub], 0.26, label=pol, color=["#285780", "#009E73", "#D55E00"][k])
    axes[1].bar(x, [r[3] for r in sub], 0.26, label=pol, color=["#285780", "#009E73", "#D55E00"][k])
for ax, title in zip(axes, ["share of queries answered by the person", "disagreement of AI-only answers"]):
    ax.set_xticks(range(3), ["AI noise 0.05", "AI noise 0.1", "AI noise 0.2"], fontsize=8)
    ax.set_title(title, fontsize=9)
    ax.legend(frameon=False, fontsize=7)
axes[1].axhline(0.3, color="0.5", ls="--", lw=0.8)

# %%
# The risk-control policy at work (medium AI)
# -------------------------------------------
# Dots: the AI's uncertainty per query; line: the threshold τ; vermilion:
# escalated; squares: random audits; dashed: cumulative share of human answers.
ei.viz.plot_escalation(traces[(0.1, "risk")])
plt.show()
