"""Shared scoring rules for the judge study. Standard library only.

Every rule here is the one declared in protocol-r1.json: agreement per non-tie expert vote (1 same pick, 0.5 judge
tie, 0 other pick), expert-to-expert agreement over ordered pairs of different raters' votes, verdicts per setup.
"""
import csv
import json
import math
import random
from collections import defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
JUDGES = ["haiku", "luna"]
FAMILY = {"haiku": {"claude-v1"}, "luna": {"gpt-4", "gpt-3.5-turbo"}}


def read_csv(name):
    with open(ROOT / "data" / name, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def load_votes():
    """{(qid, frozenset(models)): [(winner model or 'tie', rater), ...]}"""
    out = defaultdict(list)
    for v in read_csv("votes-turn1.csv"):
        w = v["winner"]
        pick = v["model_a"] if w == "model_a" else v["model_b"] if w == "model_b" else "tie"
        out[(int(v["question_id"]), frozenset((v["model_a"], v["model_b"])))].append((pick, v["rater"]))
    return dict(out)


def load_words():
    return {(int(r["question_id"]), r["model"]): int(r["words"]) for r in read_csv("answers-turn1.csv")}


def load_categories():
    return {int(r["question_id"]): r["category"] for r in read_csv("questions.csv")}


def load_replies(tag):
    """Rubric scores {judge: {(qid, model): {run: score or None}}}, pairwise picks {judge: {(qid, a, b): {order: model|'tie'}}}."""
    rubric = {j: defaultdict(dict) for j in JUDGES}
    pair = {j: defaultdict(dict) for j in JUDGES}
    unreadable = []
    for p in sorted((ROOT / "results" / "replies" / tag).glob("*.json")):
        d = json.loads(p.read_text(encoding="utf-8"))
        if not d["parsed"]:
            unreadable.append(d["name"])
        if d["kind"] == "rubric":
            rubric[d["judge"]][(d["question_id"], d["model"])][d["run"]] = d["parsed"]["score"] if d["parsed"] else None
        else:
            v = d["parsed"]["verdict"] if d["parsed"] else "tie"
            pick = d["shown_first"] if v == "A" else d["shown_second"] if v == "B" else "tie"
            pair[d["judge"]][(d["question_id"], *d["pair"])][d["order"]] = pick
    return rubric, pair, unreadable


def score_verdict(verdict, vote):
    """Agreement credit of a verdict against one non-tie vote."""
    return 1.0 if verdict == vote else 0.5 if verdict == "tie" else 0.0


def compare(sa, sb, a, b):
    if sa is None or sb is None or sa == sb:
        return "tie"
    return a if sa > sb else b


def mean(xs):
    xs = [x for x in xs if x is not None]
    return sum(xs) / len(xs) if xs else None


def var(xs):
    xs = [x for x in xs if x is not None]
    if len(xs) < 2:
        return None
    m = sum(xs) / len(xs)
    return sum((x - m) ** 2 for x in xs) / (len(xs) - 1)


class Sample:
    """One scored sample: its questions, voted pairs, replies and the verdict of every setup."""

    def __init__(self, tag, draw):
        self.tag = tag
        self.votes = load_votes()
        self.words = load_words()
        self.cats = load_categories()
        self.rubric, self.pair, self.unreadable = load_replies(tag)
        self.questions = [q["question_id"] for q in draw["questions"]]
        self.rubric_pairs = [(q["question_id"], *p) for q in draw["questions"] for p in q["rubric_pairs"]]
        self.pairwise_pairs = [(q["question_id"], *p) for q in draw["questions"] for p in q["pairwise_pairs"]]

    # verdicts: each returns the winning model or 'tie' for a pair (qid, a, b)
    def rubric_run(self, j, run):
        return lambda q, a, b: compare(self.rubric[j][(q, a)].get(run), self.rubric[j][(q, b)].get(run), a, b)

    def answer_mean(self, j, q, m, runs=(1, 2, 3)):
        return mean([self.rubric[j][(q, m)].get(r) for r in runs])

    def rubric_mean(self, j, runs=(1, 2, 3)):
        return lambda q, a, b: compare(self.answer_mean(j, q, a, runs), self.answer_mean(j, q, b, runs), a, b)

    def rubric_two(self, runs=(1, 2, 3)):
        def f(q, a, b):
            sa = mean([self.answer_mean(j, q, a, runs) for j in JUDGES])
            sb = mean([self.answer_mean(j, q, b, runs) for j in JUDGES])
            return compare(sa, sb, a, b)
        return f

    def pair_order1(self, j):
        return lambda q, a, b: self.pair[j][(q, a, b)][1]

    def pair_both(self, j):
        def f(q, a, b):
            o = self.pair[j][(q, a, b)]
            return o[1] if o[1] == o[2] else "tie"
        return f

    def pair_two(self):
        def f(q, a, b):
            s = 0
            for j in JUDGES:
                for o in (1, 2):
                    p = self.pair[j][(q, a, b)][o]
                    s += 1 if p == a else -1 if p == b else 0
            return a if s > 0 else b if s < 0 else "tie"
        return f

    def setups(self):
        """name -> (verdict function, pairs it is scored on)."""
        out = {}
        for j in JUDGES:
            out[f"{j}:rubric-run1"] = (self.rubric_run(j, 1), self.rubric_pairs)
            out[f"{j}:rubric-mean3"] = (self.rubric_mean(j), self.rubric_pairs)
            out[f"{j}:pairwise-order1"] = (self.pair_order1(j), self.pairwise_pairs)
            out[f"{j}:pairwise-both"] = (self.pair_both(j), self.pairwise_pairs)
        out["two:rubric-mean3"] = (self.rubric_two(), self.rubric_pairs)
        out["two:pairwise-4votes"] = (self.pair_two(), self.pairwise_pairs)
        # the rubric setups on the pairwise arm's pairs, for a like-for-like comparison
        for j in JUDGES:
            out[f"{j}:rubric-run1@pairwise-pairs"] = (self.rubric_run(j, 1), self.pairwise_pairs)
            out[f"{j}:rubric-mean3@pairwise-pairs"] = (self.rubric_mean(j), self.pairwise_pairs)
        out["two:rubric-mean3@pairwise-pairs"] = (self.rubric_two(), self.pairwise_pairs)
        return out

    def vote_items(self, pairs):
        """[(qid, verdict-independent tuple)] for every non-tie vote on the pairs."""
        items = []
        for (q, a, b) in pairs:
            for pick, _rater in self.votes[(q, frozenset((a, b)))]:
                if pick != "tie":
                    items.append((q, a, b, pick))
        return items

    def by_question(self, fn, pairs):
        """{qid: [credit sum, vote count]} over the non-tie votes on the pairs."""
        out = {}
        for q, a, b, pick in self.vote_items(pairs):
            c = out.setdefault(q, [0.0, 0])
            c[0] += score_verdict(fn(q, a, b), pick)
            c[1] += 1
        return out

    def agreement(self, fn, pairs):
        bq = self.by_question(fn, pairs)
        n = sum(c[1] for c in bq.values())
        return (sum(c[0] for c in bq.values()) / n, n) if n else (None, 0)

    def bootstrap(self, fn, pairs, n=2000, seed=7):
        """95% interval over questions resampled with replacement."""
        bq = self.by_question(fn, pairs)
        qs = sorted(bq)
        rng = random.Random(seed)
        vals = []
        for _ in range(n):
            pick = [rng.choice(qs) for _ in qs]
            tot = sum(bq[q][1] for q in pick)
            if tot:
                vals.append(sum(bq[q][0] for q in pick) / tot)
        vals.sort()
        return vals[int(0.025 * len(vals))], vals[int(0.975 * len(vals)) - 1]


def expert_agreement(votes, pairs=None):
    """Expert-to-expert agreement over ordered pairs of different raters' votes, first vote non-tie."""
    credits = []
    n_pairs = 0
    keys = votes.keys() if pairs is None else [(q, frozenset((a, b))) for q, a, b in pairs]
    for k in keys:
        vs = votes[k]
        if len(vs) < 2:
            continue
        n_pairs += 1
        for i, (pi, ri) in enumerate(vs):
            if pi == "tie":
                continue
            for j, (pj, rj) in enumerate(vs):
                if i != j and ri != rj:
                    credits.append(score_verdict(pj, pi))
    return (sum(credits) / len(credits) if credits else None), len(credits), n_pairs


def runs_needed(s_w2, s_jx2, d, z=1.96):
    """Runs k of one judge, and judges J at one run each, so that z*sqrt(2)*error < d."""
    bound = d * d / (2 * z * z)
    k = None if s_jx2 >= bound else max(1, math.ceil(s_w2 / (bound - s_jx2)))
    J = max(1, math.ceil((s_jx2 + s_w2) / bound))
    return k, J
