"""Score every stored judge reply against the expert votes and write results/summary.json.

Usage: python3 -I -B tools/score.py
Reads results/replies/sample1 and sample2 (sample 2 is skipped while it has no replies) and the data tables.
"""
import json
import sys
from collections import defaultdict
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import judgelib as L  # noqa: E402
import samples  # noqa: E402

ROOT = L.ROOT
PROTOCOL = json.loads((ROOT / "protocol-r1.json").read_text(encoding="utf-8"))
RUN_PAIRS = [(1, 2), (1, 3), (2, 3)]


def r4(x):
    return None if x is None else round(x, 4)


def spread(s, j):
    answers = [(q, m) for (q, m) in s.rubric[j]]
    not_equal = sum(len({s.rubric[j][a].get(r) for r in (1, 2, 3)}) > 1 for a in answers)
    variances = [L.var([s.rubric[j][a].get(r) for r in (1, 2, 3)]) for a in answers]
    s_w2 = L.mean(variances)
    changes = []
    for r1, r2 in RUN_PAIRS:
        f1, f2 = s.rubric_run(j, r1), s.rubric_run(j, r2)
        changes.append(L.mean([f1(*p) != f2(*p) for p in s.rubric_pairs]))
    return {"answers": len(answers), "share_not_all_equal": r4(not_equal / len(answers)), "within_sd": r4(s_w2 ** 0.5),
            "within_var": r4(s_w2), "verdict_change_share": r4(L.mean(changes)),
            "verdict_change_by_run_pair": [r4(c) for c in changes]}


def flips(s, j):
    n = changed = first_both = second_both = with_tie = 0
    firsts = 0
    picks = 0
    for (q, a, b) in s.pairwise_pairs:
        o = s.pair[j][(q, a, b)]
        n += 1
        # order 1 shows a first; order 2 shows b first
        for order, shown_first in ((1, a), (2, b)):
            if o[order] != "tie":
                picks += 1
                firsts += o[order] == shown_first
        if o[1] != o[2]:
            changed += 1
            if "tie" in (o[1], o[2]):
                with_tie += 1
            elif o[1] == a and o[2] == b:
                first_both += 1
            else:
                second_both += 1
    return {"pairs": n, "changed": changed, "flip_share": r4(changed / n),
            "changed_first_shown_won_both": first_both, "changed_second_shown_won_both": second_both,
            "changed_with_a_tie": with_tie,
            "share_of_changed_first_shown_won_both": r4(first_both / changed) if changed else None,
            "share_of_changed_second_shown_won_both": r4(second_both / changed) if changed else None,
            "share_of_all_picks_first_shown": r4(firsts / picks) if picks else None}


def variance_parts(s):
    """Run variance by judge, judge-by-answer variance, the judges' mean offset, the answers, and the between-question
    variance of two models' paired difference."""
    sw = {j: L.mean([L.var([s.rubric[j][a].get(r) for r in (1, 2, 3)]) for a in s.rubric[j]]) for j in L.JUDGES}
    answers = sorted(set(s.rubric["haiku"]) & set(s.rubric["luna"]))
    diffs = [s.answer_mean("haiku", *a) - s.answer_mean("luna", *a) for a in answers]
    sjx2 = max(0.0, (L.var(diffs) - (sw["haiku"] + sw["luna"]) / 3) / 2)
    offset = L.mean(diffs)
    # between-question variance of the paired difference of two models' consensus scores, pooled over model pairs
    models = sorted({m for (_q, m) in answers})
    cons = {a: L.mean([s.answer_mean(j, *a) for j in L.JUDGES]) for a in answers}
    noise = 2 * (sjx2 / 2 + L.mean(list(sw.values())) / (2 * 3))
    sq = []
    for i, m1 in enumerate(models):
        for m2 in models[i + 1:]:
            d = [cons[(q, m1)] - cons[(q, m2)] for q in s.questions if (q, m1) in cons and (q, m2) in cons]
            v = L.var(d)
            if v is not None:
                sq.append(max(0.0, v - noise))
    s_q2 = L.mean(sq)
    return sw, sjx2, offset, answers, s_q2


def components(s):
    sw, sjx2, offset, answers, s_q2 = variance_parts(s)
    m4 = PROTOCOL["measures"]["M4"]
    item = {}
    for d in m4["d_points"]:
        item[str(d)] = {j: dict(zip(("runs_one_judge", "judges_one_run"), L.runs_needed(sw[j], sjx2, d))) for j in L.JUDGES}
        item[str(d)]["pooled"] = dict(zip(("runs_one_judge", "judges_one_run"), L.runs_needed(L.mean(list(sw.values())), sjx2, d)))
    system = {}
    s_w2 = L.mean(list(sw.values()))
    for dsys in m4["d_sys_points"]:
        rows = []
        for J in m4["J_values"]:
            for k in m4["k_values"]:
                err2 = sjx2 / J + s_w2 / (J * k)
                n = 1.96 ** 2 * (s_q2 + 2 * err2) / (dsys ** 2)
                rows.append({"judges": J, "runs": k, "questions_needed": int(-(-n // 1))})
        system[str(dsys)] = rows
    return {"s_w_by_judge": {j: r4(v ** 0.5) for j, v in sw.items()}, "s_jx": r4(sjx2 ** 0.5),
            "judge_offset_haiku_minus_luna": r4(offset), "s_q": r4(s_q2 ** 0.5), "answers": len(answers),
            "item_level": item, "system_level": system}


def routing(s, floor):
    acc = []
    for (q, a, b) in s.pairwise_pairs:
        picks = {s.pair[j][(q, a, b)][o] for j in L.JUDGES for o in (1, 2)}
        if len(picks) == 1 and "tie" not in picks:
            acc.append((q, a, b))
    agree, n = s.agreement(s.pair_two(), acc)
    ee, ee_n, ee_pairs = L.expert_agreement(s.votes, acc)
    rest = [p for p in s.pairwise_pairs if p not in acc]
    return {"pairs": len(s.pairwise_pairs), "accepted": len(acc), "share_accepted": r4(len(acc) / len(s.pairwise_pairs)),
            "agreement_on_accepted": r4(agree), "votes_on_accepted": n,
            "expert_to_expert_on_accepted": r4(ee), "expert_to_expert_on_accepted_n": ee_n,
            "agreement_two_judges_on_routed": r4(s.agreement(s.pair_two(), rest)[0]),
            "expert_to_expert_on_routed": r4(L.expert_agreement(s.votes, rest)[0])}


def length_and_family(s):
    out = {}

    def longer_share(pick_list):
        n = longer = 0
        for (q, a, b, pick) in pick_list:
            wa, wb = s.words[(q, a)], s.words[(q, b)]
            if pick == "tie" or wa == wb:
                continue
            n += 1
            longer += pick == (a if wa > wb else b)
        return (r4(longer / n) if n else None), n

    def expert_picks(pairs):
        return [(q, a, b, p) for (q, a, b) in pairs for p, _r in s.votes[(q, frozenset((a, b)))]]

    out["longer_answer_share"] = {
        "experts@rubric-pairs": longer_share(expert_picks(s.rubric_pairs)),
        "experts@pairwise-pairs": longer_share(expert_picks(s.pairwise_pairs))}
    for j in L.JUDGES:
        out["longer_answer_share"][f"{j}:rubric-mean3"] = longer_share([(q, a, b, s.rubric_mean(j)(q, a, b)) for (q, a, b) in s.rubric_pairs])
        out["longer_answer_share"][f"{j}:pairwise-both"] = longer_share([(q, a, b, s.pair_both(j)(q, a, b)) for (q, a, b) in s.pairwise_pairs])
    fam = {}
    for j in L.JUDGES:
        own = L.FAMILY[j]
        pairs = [(q, a, b) for (q, a, b) in s.rubric_pairs if (a in own) != (b in own)]

        def own_share(pick_list):
            n = k = 0
            for (q, a, b, p) in pick_list:
                if p == "tie":
                    continue
                n += 1
                k += p in own
            return (r4(k / n) if n else None), n
        fam[j] = {"pairs": len(pairs), "experts": own_share(expert_picks(pairs)),
                  "judge_rubric_mean3": own_share([(q, a, b, s.rubric_mean(j)(q, a, b)) for (q, a, b) in pairs])}
        ppairs = [(q, a, b) for (q, a, b) in s.pairwise_pairs if (a in own) != (b in own)]
        fam[j]["judge_pairwise_both"] = own_share([(q, a, b, s.pair_both(j)(q, a, b)) for (q, a, b) in ppairs])
        fam[j]["experts@pairwise-pairs"] = own_share(expert_picks(ppairs))
    out["own_family_share"] = fam
    by_cat = defaultdict(dict)
    for q in s.questions:
        c = s.cats[q]
        for name, (fn, pairs) in s.setups().items():
            if name in ("haiku:rubric-mean3", "luna:rubric-mean3", "haiku:pairwise-both", "luna:pairwise-both", "two:pairwise-4votes", "two:rubric-mean3"):
                ps = [p for p in pairs if p[0] == q]
                v, n = s.agreement(fn, ps)
                by_cat[c][name] = [r4(v), n]
        ee = L.expert_agreement(s.votes, [p for p in s.rubric_pairs if p[0] == q])
        by_cat[c]["expert_to_expert@rubric-pairs"] = [r4(ee[0]), ee[1]]
    out["by_category"] = dict(by_cat)
    return out


def gate(s, m1, sp, fl, floor):
    lim_f, lim_r = PROTOCOL["gate"]["max_order_flip_share"], PROTOCOL["gate"]["max_rerun_change_share"]
    out = {}
    for name, rec in m1.items():
        if "@" in name:
            continue
        j, setup = name.split(":")
        checks = {"agreement": [rec["agreement"], ">=", r4(floor), rec["agreement"] >= floor]}
        if j in L.JUDGES and setup == "rubric-run1":
            v = sp[j]["verdict_change_share"]
            checks["rerun_change"] = [v, "<=", lim_r, v <= lim_r]
        if j in L.JUDGES and setup.startswith("pairwise"):
            v = fl[j]["flip_share"]
            checks["order_flip"] = [v, "<=", lim_f, v <= lim_f]
        out[name] = {"pass": all(c[3] for c in checks.values()), "checks": checks}
    return out


def score_sample(tag, draw, floor):
    s = L.Sample(tag, draw)
    m1 = {}
    for name, (fn, pairs) in s.setups().items():
        v, n = s.agreement(fn, pairs)
        lo, hi = s.bootstrap(fn, pairs)
        m1[name] = {"agreement": r4(v), "votes": n, "pairs": len(pairs), "ci95": [r4(lo), r4(hi)]}
    ee_r = L.expert_agreement(s.votes, s.rubric_pairs)
    ee_p = L.expert_agreement(s.votes, s.pairwise_pairs)
    sp = {j: spread(s, j) for j in L.JUDGES}
    fl = {j: flips(s, j) for j in L.JUDGES}
    return {
        "questions": [{"question_id": q, "category": s.cats[q]} for q in s.questions],
        "rubric_pairs": len(s.rubric_pairs), "pairwise_pairs": len(s.pairwise_pairs),
        "unreadable_replies": s.unreadable,
        "expert_to_expert": {"rubric_pairs": {"agreement": r4(ee_r[0]), "comparisons": ee_r[1], "multi_vote_pairs": ee_r[2]},
                             "pairwise_pairs": {"agreement": r4(ee_p[0]), "comparisons": ee_p[1], "multi_vote_pairs": ee_p[2]}},
        "M1_agreement": m1, "M2_spread": sp, "M3_order": fl, "M4_needed": components(s),
        "M5_routing": routing(s, floor), "M6_errors": length_and_family(s),
        "gate": gate(s, m1, sp, fl, floor)}


def predictions(full_ee, res):
    s1 = res.get("sample1")
    s2 = res.get("sample2")
    out = []

    def add(pid, held, value):
        out.append({"id": pid, "result": "held" if held else "missed", "value": value})
    add("P1", 0.60 <= full_ee <= 0.75, r4(full_ee))
    floor = full_ee - 0.05
    v = {j: s1["M1_agreement"][f"{j}:pairwise-both"]["agreement"] for j in L.JUDGES}
    add("P2", all(x >= floor for x in v.values()), v)
    v = {j: [s1["M1_agreement"][f"{j}:rubric-mean3"]["agreement"], s1["M1_agreement"][f"{j}:rubric-run1"]["agreement"]] for j in L.JUDGES}
    add("P3", all(a >= b for a, b in v.values()), v)
    v = {j: s1["M3_order"][j]["flip_share"] for j in L.JUDGES}
    add("P4", all(0.10 <= x <= 0.30 for x in v.values()), v)
    v = {j: s1["M2_spread"][j]["share_not_all_equal"] for j in L.JUDGES}
    add("P5", all(0.20 <= x <= 0.60 for x in v.values()), v)
    v = {j: s1["M2_spread"][j]["within_sd"] for j in L.JUDGES}
    add("P6", all(x < 1 for x in v.values()), v)
    c = s1["M4_needed"]
    add("P7", c["s_jx"] > max(c["s_w_by_judge"].values()), {"s_jx": c["s_jx"], "s_w": c["s_w_by_judge"]})
    r = s1["M5_routing"]
    add("P8", r["share_accepted"] >= 0.5 and r["agreement_on_accepted"] >= full_ee,
        {"share_accepted": r["share_accepted"], "agreement_on_accepted": r["agreement_on_accepted"]})
    held9 = False
    vals9 = {}
    for j in L.JUDGES:
        f = s1["M3_order"][j]
        if f["changed"] >= 5:
            top = max(f["changed_first_shown_won_both"], f["changed_second_shown_won_both"]) / f["changed"]
            vals9[j] = r4(top)
            held9 = held9 or top >= 0.65
    add("P9", held9, vals9)
    la = s1["M6_errors"]["longer_answer_share"]
    v10 = {}
    held10 = True
    for j in L.JUDGES:
        d1 = la[f"{j}:rubric-mean3"][0] - la["experts@rubric-pairs"][0]
        d2 = la[f"{j}:pairwise-both"][0] - la["experts@pairwise-pairs"][0]
        v10[j] = [r4(d1), r4(d2)]
        held10 = held10 and d1 >= 0.05 and d2 >= 0.05
    add("P10", held10, v10)
    if s2:
        ok = True
        v11 = {}
        for j in L.JUDGES:
            a1 = s1["M1_agreement"][f"{j}:pairwise-both"]["agreement"]
            a2 = s2["M1_agreement"][f"{j}:pairwise-both"]["agreement"]
            c1 = s1["M2_spread"][j]["verdict_change_share"]
            c2 = s2["M2_spread"][j]["verdict_change_share"]
            v11[j] = {"agreement": [a1, a2], "rerun_change": [c1, c2]}
            ok = ok and abs(a2 - a1) <= 0.10 and abs(c2 - c1) <= 0.15
        same = {k: [s1["gate"][k]["pass"], s2["gate"][k]["pass"]] for k in s1["gate"]}
        v11["gates_same"] = all(a == b for a, b in same.values())
        v11["gates"] = same
        add("P11", ok and v11["gates_same"], v11)
    else:
        out.append({"id": "P11", "result": "untestable", "value": "sample 2 not scored"})
    return out


def main():
    votes = L.load_votes()
    full = L.expert_agreement(votes)
    floor = full[0] - 0.05
    res = {"expert_to_expert_all_turn1": {"agreement": r4(full[0]), "comparisons": full[1], "multi_vote_pairs": full[2]},
           "gate_floor": r4(floor)}
    for n in (1, 2):
        tag = f"sample{n}"
        draw = samples.draw(n)
        expected = sum(6 * 3 * 2 + 4 * len(q["pairwise_pairs"]) for q in draw["questions"])
        have = len(list((ROOT / "results" / "replies" / tag).glob("*.json")))
        if have < expected:
            print(f"{tag}: {have} of {expected} replies stored; not scored")
            continue
        res[tag] = score_sample(tag, draw, floor)
    res["predictions"] = predictions(full[0], res)
    out = ROOT / "results" / "summary.json"
    out.write_text(json.dumps(res, indent=1) + "\n", encoding="utf-8")
    print(f"wrote {out.relative_to(ROOT)}: expert-to-expert {res['expert_to_expert_all_turn1']}; samples "
          f"{[k for k in res if k.startswith('sample')]}")


if __name__ == "__main__":
    main()
