"""
An AI judge in the loop: prompts, images and debiasing
======================================================

:class:`~easyiec.evaluators.LLMJudge` turns a query into a prompt for a
language or vision–language model: the goal, the protocol, the candidates as
labelled images (or text), and a JSON schema for the answer. Because LLM judges
prefer the first or the second option more often than chance (Zheng et al.,
2023; Shi et al., 2024), the judge can ask several times with the candidates in
reversed or permuted order and aggregate the answers. Here the model is the
offline :class:`~easyiec.evaluators.MockJudgeClient`, whose taste and biases we
control; with an API key the same code runs with Claude (see the last section
of the gallery).
"""

# %%
# What the model receives
# -----------------------
import matplotlib.pyplot as plt
import numpy as np

import easyiec as ei
from easyiec.evaluators import LLMJudge, MockJudgeClient
from easyiec.imaging import decode_png
from easyiec.problems import JuliaSet
from easyiec.strategies import InteractiveGA
from easyiec.validation import make_individuals

problem = JuliaSet()
target = problem.random(np.random.default_rng(5))
taste = lambda g: problem.utility(g, target)  # noqa: E731  the mock judge's hidden taste
client = MockJudgeClient(scorer=taste, score_on="genome", noise=0.05, position_bias=0.05, seed=1)
judge = LLMJudge(client, problem, goal="an intricate, glowing spiral in cool colours", debias="reverse", n_views=2,
                 image_size=128)
items = make_individuals(problem.random(np.random.default_rng(0), 6))
fb = judge.evaluate(ei.Query("select", items, n_select=2))
print(fb.summary())
print("rationale:", fb.rationale[:120])
print("uncertainty:", fb.uncertainty, " cost:", fb.cost)
# %%
# The two requests of the last answer: the system prompt, the instruction and
# the composite image, once in the original and once in reversed order.
views = client.requests[-2:]
print(views[0].system[:300], "...")
print("\n".join(v for k, v in views[0].parts if k == "text")[:900], "...")
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4))
for ax, req, title in zip(axes, views, ["first view", "second view (order reversed)"]):
    ax.imshow(decode_png(next(v for k, v in req.parts if k == "image")))
    ax.set_title(title, fontsize=9)
    ax.axis("off")

# %%
# Position bias and what reversal buys
# ------------------------------------
# A judge whose first-shown option gets a bonus of 0.1 on the utility scale is
# asked about 80 pairs, once (``debias="none"``) or twice in both orders. Asked
# once, it prefers the first option far more often than half of the time.
# Reversal cannot make the judge see better; it removes the systematic
# preference and turns order-dependent verdicts into ties with high
# uncertainty — exactly the cases a hybrid evaluator should pass to a person.
pairs = [make_individuals(problem.random(np.random.default_rng(100 + k), 2)) for k in range(80)]
truth = np.array([taste(a.genome) > taste(b.genome) for a, b in pairs])
stats = {}
for mode in ["none", "reverse"]:
    j = LLMJudge(MockJudgeClient(scorer=taste, score_on="genome", noise=0.05, position_bias=0.1, seed=2),
                 problem, debias=mode, image_size=48)
    r = np.array([j.evaluate(ei.Query("pairs", [a, b])).pair_results[0][2] for a, b in pairs])
    decided = r != 0.5
    stats[mode] = {"first option chosen": np.mean(r[decided] > 0.5),
                   "accuracy (decided pairs)": np.mean((r[decided] > 0.5) == truth[decided]),
                   "flagged as tie": 1 - decided.mean()}
print(stats)
fig, ax = plt.subplots(figsize=(6.4, 3))
keys = list(stats["none"])
x = np.arange(len(keys))
ax.bar(x - 0.18, [stats["none"][k] for k in keys], 0.36, label="asked once", color="#D55E00")
ax.bar(x + 0.18, [stats["reverse"][k] for k in keys], 0.36, label="both orders", color="#285780")
ax.axhline(truth.mean(), color="0.6", lw=0.8, ls="--")
ax.text(2.45, truth.mean() + 0.02, "true share of\nfirst-better pairs", fontsize=7, color="0.4", ha="right")
ax.set_xticks(x, keys, fontsize=8)
ax.legend(frameon=False, fontsize=8)
ax.set_title("a position-biased judge, 80 pairs", fontsize=9)

# %%
# The judge drives a whole session
# --------------------------------
res = ei.run(problem, InteractiveGA(pop_size=9), judge, generations=10, seed=1, oracle=taste)
ei.viz.plot_anytime(res, label="mock LLM judge")
print(res.summary())
plt.show()
