"""Tests: the scoring rules on small made-up cases, the samples against the stored replies, and a replay of every result
from the stored replies with no model call. Usage: python3 -I -B tests/test_judge.py
"""
import json
import sys
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tools"))
import judgelib as L  # noqa: E402
import samples  # noqa: E402
import score  # noqa: E402
import changes_r1  # noqa: E402


class Rules(unittest.TestCase):
    def test_credit(self):
        self.assertEqual(L.score_verdict("gpt-4", "gpt-4"), 1.0)
        self.assertEqual(L.score_verdict("tie", "gpt-4"), 0.5)
        self.assertEqual(L.score_verdict("llama-13b", "gpt-4"), 0.0)

    def test_compare(self):
        self.assertEqual(L.compare(8, 3, "a", "b"), "a")
        self.assertEqual(L.compare(3, 8, "a", "b"), "b")
        self.assertEqual(L.compare(5, 5, "a", "b"), "tie")
        self.assertEqual(L.compare(None, 5, "a", "b"), "tie")

    def test_expert_agreement(self):
        votes = {(1, frozenset(("a", "b"))): [("a", "r1"), ("a", "r2"), ("tie", "r3")],
                 (2, frozenset(("a", "b"))): [("b", "r1")]}
        # ordered pairs with a non-tie first vote: r1->r2 (1), r1->r3 (0.5), r2->r1 (1), r2->r3 (0.5); pair 2 has one vote
        agree, n, pairs = L.expert_agreement(votes)
        self.assertEqual((agree, n, pairs), (0.75, 4, 1))

    def test_same_rater_twice_is_not_compared(self):
        votes = {(1, frozenset(("a", "b"))): [("a", "r1"), ("b", "r1")]}
        self.assertEqual(L.expert_agreement(votes)[1], 0)

    def test_runs_needed(self):
        # no judge-by-answer spread: k from run noise alone; bound = 1/(2*1.96^2) = 0.1302
        k, J = L.runs_needed(0.25, 0.0, 1.0)
        self.assertEqual(k, 2)
        self.assertEqual(J, 2)
        # judge-by-answer variance above the bound: no number of runs is enough
        k, J = L.runs_needed(0.25, 0.2, 1.0)
        self.assertIsNone(k)
        self.assertEqual(J, 4)


class Changes(unittest.TestCase):
    def test_reference_items(self):
        # pair (1, a, b): rater x picks a, rater y picks b, rater z calls a tie; pair (2, a, c): one vote only
        votes = {(1, frozenset(("a", "b"))): [("a", "x"), ("b", "y"), ("tie", "z")],
                 (2, frozenset(("a", "c"))): [("a", "x")]}
        items = changes_r1.reference_items(votes, [(1, "a", "b"), (2, "a", "c")])
        # the tie is never a reference; each decided vote scores the mean credit of the other raters against it
        self.assertEqual(items, [(1, "a", "b", "a", 0.25), (1, "a", "b", "b", 0.25)])

    def test_gap_range_constant_gap(self):
        bq = {"q1": [2.0, 1.0, 2], "q2": [4.0, 2.0, 4], "q3": [1.0, 0.5, 1]}
        g = changes_r1.gap_ranges(bq)
        self.assertAlmostEqual(g["gap"], 0.5)
        self.assertEqual(g["t95"], [0.5, 0.5])
        self.assertEqual(g["boot95"], [0.5, 0.5])

    def test_power_sizes(self):
        s = L.Sample("sample1", samples.draw(1))
        for r in changes_r1.sizes(s):
            ratio = r["questions_power80"] / r["questions_interval95"]
            self.assertAlmostEqual(ratio, (1.96 + 0.8416) ** 2 / 1.96 ** 2, delta=0.05)

    def test_replay_matches_changes(self):
        stored = json.loads((ROOT / "results" / "changes-r1.json").read_text(encoding="utf-8"))
        self.assertEqual(json.loads(json.dumps(changes_r1.compute())), stored)


class Stored(unittest.TestCase):
    def test_replies_match_samples(self):
        for n in (1, 2):
            d = samples.draw(n)
            names = {p.stem for p in (ROOT / "results" / "replies" / f"sample{n}").glob("*.json")}
            want = set()
            for q in d["questions"]:
                models = sorted({m for pr in q["rubric_pairs"] for m in pr})
                self.assertEqual(len(models), 6)
                for j in L.JUDGES:
                    want |= {f"{j}-rubric-q{q['question_id']}-{m}-run{r}" for m in models for r in (1, 2, 3)}
                    for a, b in q["pairwise_pairs"]:
                        want |= {f"{j}-pairwise-q{q['question_id']}-{a}-vs-{b}-order{o}" for o in (1, 2)}
            self.assertEqual(names, want, f"sample {n}")

    def test_samples_disjoint(self):
        s1 = {q["question_id"] for q in samples.draw(1)["questions"]}
        s2 = {q["question_id"] for q in samples.draw(2)["questions"]}
        self.assertFalse(s1 & s2)
        self.assertNotIn(81, s1 | s2)

    def test_prompt_hash_pinned(self):
        import hashlib
        proto = json.loads((ROOT / "protocol-r1.json").read_text(encoding="utf-8"))
        self.assertEqual(hashlib.sha256((ROOT / "tools" / "prompts.py").read_bytes()).hexdigest(), proto["prompts"]["sha256"])
        for n in (1, 2):
            for p in (ROOT / "results" / "replies" / f"sample{n}").glob("*.json"):
                d = json.loads(p.read_text(encoding="utf-8"))
                self.assertEqual(len(d["prompt_sha256"]), 64)

    def test_replay_matches_summary(self):
        stored = json.loads((ROOT / "results" / "summary.json").read_text(encoding="utf-8"))
        votes = L.load_votes()
        full = L.expert_agreement(votes)
        floor = full[0] - 0.05
        self.assertAlmostEqual(stored["expert_to_expert_all_turn1"]["agreement"], round(full[0], 4))
        for n in (1, 2):
            fresh = score.score_sample(f"sample{n}", samples.draw(n), floor)
            self.assertEqual(json.loads(json.dumps(fresh)), stored[f"sample{n}"], f"sample {n}")


if __name__ == "__main__":
    unittest.main(verbosity=1)
