"""The changes declared after the results, before any code for them, computed from the stored replies with no
model call.

1.  rerun and order-change shares with unreadable replies left out, beside the declared values;
2.  the gap between a setup and a second expert on identical reference votes, with two 95% ranges;
3.  questions needed for a half-point gap at 80% power, beside the 95%-interval figure of round 1;
4.  the gate with the agreement floor set from the same pairs, noise checks as declared and as in 1;
and the predictions Q1 to Q5 and the rule for the call declared with them, scored.
results/summary.json is not touched. Writes results/changes-r1.json.

Usage: python3 -I -B tools/changes_r1.py
"""
import json
import math
import random
import sys
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

Z_A, Z_B = 1.96, 0.8416  # two-sided 5% test, 80% power
# 97.5th percentile of Student's t by degrees of freedom
T975 = {1: 12.706, 2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571, 6: 2.447, 7: 2.365, 8: 2.306, 9: 2.262, 10: 2.228,
        11: 2.201, 12: 2.179, 13: 2.160, 14: 2.145, 15: 2.131, 16: 2.120, 17: 2.110, 18: 2.101, 19: 2.093, 20: 2.086}
GAP_SETUPS = ["two:pairwise-4votes", "haiku:pairwise-both", "luna:pairwise-both", "haiku:pairwise-order1",
              "luna:pairwise-order1", "two:rubric-mean3@pairwise-pairs", "haiku:rubric-mean3@pairwise-pairs",
              "luna:rubric-mean3@pairwise-pairs", "haiku:rubric-run1@pairwise-pairs", "luna:rubric-run1@pairwise-pairs"]
r4 = score.r4


def unreadable(tag):
    """Unreadable score replies {(judge, qid, model, run)} and picks {(judge, qid, a, b, order)}."""
    rub, pick = set(), set()
    for p in sorted((ROOT / "results" / "replies" / tag).glob("*.json")):
        d = json.loads(p.read_text(encoding="utf-8"))
        if d["parsed"]:
            continue
        if d["kind"] == "rubric":
            rub.add((d["judge"], d["question_id"], d["model"], d["run"]))
        else:
            pick.add((d["judge"], d["question_id"], *d["pair"], d["order"]))
    return rub, pick


def rerun_left_out(s, j, bad):
    shares, kept = [], []
    for r1, r2 in score.RUN_PAIRS:
        f1, f2 = s.rubric_run(j, r1), s.rubric_run(j, r2)
        ps = [p for p in s.rubric_pairs if not any((j, p[0], m, r) in bad for m in p[1:] for r in (r1, r2))]
        shares.append(L.mean([f1(*p) != f2(*p) for p in ps]))
        kept.append(len(ps))
    return {"verdict_change_share": r4(L.mean(shares)), "by_run_pair": [r4(x) for x in shares],
            "pairs_kept_by_run_pair": kept, "pairs": len(s.rubric_pairs)}


def flips_left_out(s, j, bad):
    ps = [p for p in s.pairwise_pairs if not any((j, *p, o) in bad for o in (1, 2))]
    changed = sum(s.pair[j][p][1] != s.pair[j][p][2] for p in ps)
    return {"pairs": len(ps), "changed": changed, "flip_share": r4(changed / len(ps))}


def reference_items(votes, pairs):
    """[(qid, a, b, reference pick, the other raters' mean credit against it)] over decided votes that have a vote
    from at least one other rater on the same pair."""
    out = []
    for (q, a, b) in pairs:
        vs = votes[(q, frozenset((a, b)))]
        for pi, ri in vs:
            if pi == "tie":
                continue
            others = [pj for pj, rj in vs if rj != ri]
            if others:
                out.append((q, a, b, pi, L.mean([L.score_verdict(pj, pi) for pj in others])))
    return out


def gap_by_question(fn, items, key):
    """{question key: [judge credit sum, expert credit sum, reference votes]}."""
    out = {}
    for q, a, b, pick, ex in items:
        c = out.setdefault(key(q), [0.0, 0.0, 0])
        c[0] += L.score_verdict(fn(q, a, b), pick)
        c[1] += ex
        c[2] += 1
    return out


def gap_ranges(bq, n=2000, seed=7):
    qs = sorted(bq)
    w = sum(c[2] for c in bq.values())
    judge = sum(c[0] for c in bq.values()) / w
    expert = sum(c[1] for c in bq.values()) / w
    gap = judge - expert
    rng = random.Random(seed)
    vals = []
    for _ in range(n):
        pick = [rng.choice(qs) for _ in qs]
        tot = sum(bq[q][2] for q in pick)
        vals.append(sum(bq[q][0] - bq[q][1] for q in pick) / tot)
    vals.sort()
    boot = (vals[int(0.025 * len(vals))], vals[int(0.975 * len(vals)) - 1])
    k = len(qs)
    resid = [(bq[q][0] - bq[q][1]) - gap * bq[q][2] for q in qs]
    se = math.sqrt(k / (k - 1) * sum(e * e for e in resid)) / w
    t = T975[k - 1]
    return {"setup_agreement": r4(judge), "expert_agreement": r4(expert), "gap": r4(gap), "reference_votes": w,
            "questions": k, "boot95": [r4(boot[0]), r4(boot[1])], "t95": [r4(gap - t * se), r4(gap + t * se)],
            "lower": r4(min(boot[0], gap - t * se))}


def sizes(s):
    sw, sjx2, _offset, _answers, s_q2 = score.variance_parts(s)
    m4 = score.PROTOCOL["measures"]["M4"]
    s_w2 = L.mean(list(sw.values()))
    rows = []
    for dsys in m4["d_sys_points"]:
        for J in m4["J_values"]:
            for k in m4["k_values"]:
                err2 = sjx2 / J + s_w2 / (J * k)
                var = s_q2 + 2 * err2
                rows.append({"d": dsys, "judges": J, "runs": k,
                             "questions_interval95": math.ceil(1.96 ** 2 * var / dsys ** 2),
                             "questions_power80": math.ceil((Z_A + Z_B) ** 2 * var / dsys ** 2)})
    return rows


def same_pairs_gate(s, m1, sp, fl, c1_rerun, c1_flip):
    lim_f, lim_r = score.PROTOCOL["gate"]["max_order_flip_share"], score.PROTOCOL["gate"]["max_rerun_change_share"]
    floor = {"rubric": L.expert_agreement(s.votes, s.rubric_pairs)[0] - 0.05,
             "pairwise": L.expert_agreement(s.votes, s.pairwise_pairs)[0] - 0.05}
    out = {}
    for name, rec in m1.items():
        if "@" in name:
            continue
        j, setup = name.split(":")
        f = floor["pairwise" if setup.startswith("pairwise") else "rubric"]
        row = {"agreement": rec["agreement"], "floor_same_pairs": r4(f), "agreement_pass": rec["agreement"] >= f}
        noise, noise_c1 = True, True
        if j in L.JUDGES and setup == "rubric-run1":
            noise = sp[j]["verdict_change_share"] <= lim_r
            noise_c1 = c1_rerun[j]["verdict_change_share"] <= lim_r
        if j in L.JUDGES and setup.startswith("pairwise"):
            noise = fl[j]["flip_share"] <= lim_f
            noise_c1 = c1_flip[j]["flip_share"] <= lim_f
        row["pass_declared_noise"] = row["agreement_pass"] and noise
        row["pass_c1_noise"] = row["agreement_pass"] and noise_c1
        out[name] = row
    return out


def compute():
    stored = json.loads((ROOT / "results" / "summary.json").read_text(encoding="utf-8"))
    votes = L.load_votes()
    res, pooled = {}, {name: {} for name in GAP_SETUPS}
    for n in (1, 2):
        tag = f"sample{n}"
        s = L.Sample(tag, samples.draw(n))
        bad_rub, bad_pick = unreadable(tag)
        c1_rerun = {j: rerun_left_out(s, j, bad_rub) for j in L.JUDGES}
        c1_flip = {j: flips_left_out(s, j, bad_pick) for j in L.JUDGES}
        items = reference_items(votes, s.pairwise_pairs)
        setups = s.setups()
        gaps = {}
        for name in GAP_SETUPS:
            bq = gap_by_question(setups[name][0], items, lambda q, t=tag: f"{t}:q{q}")
            gaps[name] = gap_ranges(bq)
            pooled[name].update(bq)
        m1, sp, fl = stored[tag]["M1_agreement"], stored[tag]["M2_spread"], stored[tag]["M3_order"]
        res[tag] = {"unreadable": {"scores": len(bad_rub), "picks": len(bad_pick)},
                    "change1_rerun": {j: dict(c1_rerun[j], declared=sp[j]["verdict_change_share"]) for j in L.JUDGES},
                    "change1_order": {j: dict(c1_flip[j], declared=fl[j]["flip_share"], declared_changed=fl[j]["changed"],
                                         declared_pairs=fl[j]["pairs"]) for j in L.JUDGES},
                    "change2_gap": gaps, "change3_sizes": sizes(s),
                    "change4_gate_same_pairs": same_pairs_gate(s, m1, sp, fl, c1_rerun, c1_flip)}
    res["pooled"] = {"change2_gap": {name: gap_ranges(bq) for name, bq in pooled.items()}}
    lim = 0.20
    s1, s2 = res["sample1"], res["sample2"]
    q1 = s2["change1_rerun"]["haiku"]["verdict_change_share"] < lim and (
        (s1["change1_rerun"]["haiku"]["verdict_change_share"] <= lim) == (s2["change1_rerun"]["haiku"]["verdict_change_share"] <= lim)) and (
        (s1["change1_rerun"]["luna"]["verdict_change_share"] <= lim) != (s2["change1_rerun"]["luna"]["verdict_change_share"] <= lim))
    q2 = (s1["change1_order"]["haiku"]["changed"], s1["change1_order"]["haiku"]["pairs"]) == (3, 28)
    pg = res["pooled"]["change2_gap"]["two:pairwise-4votes"]
    q3 = -0.02 <= pg["gap"] <= 0.06 and pg["lower"] < -0.05
    one = [r for s in (s1, s2) for r in s["change3_sizes"] if r["judges"] == 1 and r["runs"] == 1 and r["d"] == 0.5]
    q4 = all(160 <= r["questions_power80"] <= 280 for r in one)
    g1, g2 = s1["change4_gate_same_pairs"], s2["change4_gate_same_pairs"]
    q5 = (not g1["haiku:rubric-run1"]["agreement_pass"] and not g2["luna:pairwise-both"]["agreement_pass"]
          and all(g[k]["agreement_pass"] for g in (g1, g2) for k in ("two:rubric-mean3", "two:pairwise-4votes")))
    res["predictions"] = {k: ("held" if v else "missed") for k, v in
                          (("Q1", q1), ("Q2", q2), ("Q3", q3), ("Q4", q4), ("Q5", q5))}
    res["call"] = {"lower": pg["lower"], "bar": -0.05,
                   "decision": "stays" if pg["lower"] >= -0.05 else "narrows"}
    return res


def main():
    res = compute()
    out = ROOT / "results" / "changes-r1.json"
    out.write_text(json.dumps(res, indent=1) + "\n", encoding="utf-8")
    print(f"wrote {out.relative_to(ROOT)}: call {res['call']}; predictions {res['predictions']}")


if __name__ == "__main__":
    main()
