"""
Auditing a judge before trusting it
===================================

Before an AI judge replaces people, its answers should pass basic checks of
measurement quality. :func:`~easyiec.validation.audit_judge` runs four of
them: the *swap test* (does the verdict survive reversing the presentation
order?), the share of wins of the first-shown option, *transitivity* of a full
round robin (Kendall and Babington Smith's coefficient of consistency ζ,
computed from the number of cyclic triads) and *self-consistency* of repeated
answers.
"""

# %%
# Four judges with known defects
# ------------------------------
# A careful mock judge, one with strong position bias, one with noisy judgment
# and, for reference, a simulated person.
import matplotlib.pyplot as plt
import numpy as np

import easyiec as ei
from easyiec.evaluators import LLMJudge, MockJudgeClient
from easyiec.problems import JuliaSet
from easyiec.validation import audit_judge

problem = JuliaSet()
target = problem.random(np.random.default_rng(5))
taste = lambda g: problem.utility(g, target)  # noqa: E731
judges = {
    "careful AI": LLMJudge(MockJudgeClient(taste, score_on="genome", noise=0.03, seed=1), problem, debias="none",
                           image_size=48, name="careful AI"),
    "position-biased AI": LLMJudge(MockJudgeClient(taste, score_on="genome", noise=0.03, position_bias=0.2, seed=2),
                                   problem, debias="none", image_size=48, name="position-biased AI"),
    "noisy AI": LLMJudge(MockJudgeClient(taste, score_on="genome", noise=0.25, seed=3), problem, debias="none",
                         image_size=48, name="noisy AI"),
    "simulated person": ei.SimulatedUser(problem, target=target, noise=0.05, seed=4, name="simulated person"),
}
audits = [audit_judge(j, problem, goal="Choose the image you find more beautiful.", n_pairs=20, n_items=7)
          for j in judges.values()]
for a in audits:
    print({k: (round(v, 2) if isinstance(v, float) else v) for k, v in a.summary().items()})
ei.viz.plot_judge_audit(audits, fig=plt.figure(figsize=(10, 2.8)))

# %%
# Position bias seen in a session log
# -----------------------------------
# :func:`~easyiec.validation.position_bias` needs no extra queries: it counts,
# over a logged session, how often each display position was chosen and tests
# the counts against uniformity (χ² test). The galleries must not be ordered by
# the strategy (most strategies show the survivors first), so random galleries
# are used here. The biased judge favours the first tiles.
from easyiec.strategies import RandomSearch  # noqa: E402
from easyiec.validation import position_bias  # noqa: E402

fig, axes = plt.subplots(1, 2, figsize=(8, 3))
for ax, name in zip(axes, ["careful AI", "position-biased AI"]):
    res = ei.run(problem, RandomSearch(pop_size=9), judges[name], generations=20, seed=1, oracle=taste)
    pb = position_bias(res.log)
    ei.viz.plot_position_bias(pb, ax=ax, title=f"{name} (χ² p = {pb['p_value']:.2g})")
plt.show()
