"""Turn stored codes and unsealed levels into results/summary.json. Replays with no key and no network.

Usage: python3 -I -B tools/summarize.py [draws]
Quote checks need the redacted text, so they are computed once by tools/check_quotes.py and read from results/quote_checks.json.
"""
import json
import sys
from collections import Counter
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tools"))
import agreement as ag  # noqa: E402
import rule  # noqa: E402

DRAWS = int(sys.argv[1]) if len(sys.argv) > 1 else 20000
QS = ("decides", "affects", "review", "data")
TIERS = [1, 2, 3, 4]
ORDER = {q: rule.QUESTIONS[q]["order"] for q in QS}


def load():
    cases = json.loads((ROOT / "data" / "cases.json").read_text(encoding="utf-8"))
    controls = json.loads((ROOT / "data" / "controls.json").read_text(encoding="utf-8"))["controls"]
    levels = json.loads((ROOT / "results" / "levels.json").read_text(encoding="utf-8"))
    codes = {}
    for coder in "AB":
        for run in (1, 2):
            for f in sorted((ROOT / "results" / "codes" / coder).glob(f"*-run{run}.json")):
                d = json.loads(f.read_text(encoding="utf-8"))
                codes[(coder, d["case_id"], run)] = d
    held = ROOT / "results" / "held_back_codes.json"
    if held.exists():  # a stored reply left out of the download replays from its answers
        for d in json.loads(held.read_text(encoding="utf-8"))["rows"]:
            codes.setdefault((d["coder"], d["case_id"], d["run"]), d)
    return cases, controls, levels, codes


def answers(row):
    return {q: row["codes"][q]["answer"] for q in QS}


def tier_of(row):
    return rule.tier_from_codes(answers(row))


def single_changes(ans, target):
    out = []
    for q in QS:
        for v in ORDER[q]:
            if v != ans[q] and rule.tier_from_codes({**ans, q: v}) == target:
                out.append({"question": q, "from": ans[q], "to": v})
    return out


def edge_distance(current):
    """Distance in points of 100 from the nearest band edge, on the current tool's maximum of 169. None without a score."""
    if current is None:
        return None
    pct = 100 * current / 169
    return min(abs(pct - e) for e in (25.5, 50.5, 75.5))


def pct_band(current):
    if current is None:
        return None
    pct = 100 * current / 169
    return 1 if pct <= 25.5 else 2 if pct <= 50.5 else 3 if pct <= 75.5 else 4


def main():
    cases, controls, levels, codes = load()
    rows = cases["cases"]
    ids = [c["case_id"] for c in rows]
    title = {c["case_id"]: c["title"] for c in rows}
    levels = {i: levels[i] for i in ids}
    lv = [levels[i]["level"] for i in ids]
    assert all(v in TIERS for v in lv)
    dist = Counter(lv)
    modal, modal_n = dist.most_common(1)[0]
    out = {"cases": len(ids), "left_out": cases["left_out"], "level_distribution": {str(k): dist.get(k, 0) for k in TIERS},
           "baseline": {"always_level": modal, "exact": modal_n, "exact_pct": 100 * modal_n / len(ids),
                        "exact_ci_pct": [100 * v for v in ag.wilson(modal_n, len(ids))],
                        "within_one": sum(abs(v - modal) <= 1 for v in lv), "kappa": 0.0}}
    t = {c: {i: tier_of(codes[(c, i, 1)]) for i in ids if (c, i, 1) in codes} for c in "AB"}
    a = {c: {i: answers(codes[(c, i, 1)]) for i in ids if (c, i, 1) in codes} for c in "AB"}
    out["coded"] = {c: len(t[c]) for c in "AB"}
    out["rule_vs_level"] = {}
    for c in "AB":
        have = [i for i in ids if i in t[c]]
        x, y = [t[c][i] for i in have], [levels[i]["level"] for i in have]
        cmp_ = ag.compare(x, y, TIERS, True, DRAWS)
        cmp_["within_one"] = sum(abs(p - q) <= 1 for p, q in zip(x, y))
        cmp_["within_one_ci_pct"] = [100 * v for v in ag.wilson(cmp_["within_one"], len(have))]
        cmp_["above"] = sum(p > q for p, q in zip(x, y))
        cmp_["below"] = sum(p < q for p, q in zip(x, y))
        cmp_["above_two_or_more"] = sum(p - q >= 2 for p, q in zip(x, y))
        cmp_["tier_distribution"] = {str(k): x.count(k) for k in TIERS}
        cmp_["matrix"] = [[sum(1 for p, q in zip(x, y) if p == r_ and q == l_) for l_ in TIERS] for r_ in TIERS]
        out["rule_vs_level"][c] = cmp_
    both = [i for i in ids if i in t["A"] and i in t["B"] and t["A"][i] == t["B"][i]]
    bx, by = [t["A"][i] for i in both], [levels[i]["level"] for i in both]
    cb = ag.compare(bx, by, TIERS, True, DRAWS)
    cb.update(above=sum(p > q for p, q in zip(bx, by)), below=sum(p < q for p, q in zip(bx, by)),
              within_one=sum(abs(p - q) <= 1 for p, q in zip(bx, by)))
    out["rule_vs_level_where_coders_agree"] = cb
    shared = [i for i in ids if i in t["A"] and i in t["B"]]
    cc = ag.compare([t["A"][i] for i in shared], [t["B"][i] for i in shared], TIERS, True, DRAWS)
    cc["within_one"] = sum(abs(t["A"][i] - t["B"][i]) <= 1 for i in shared)
    cc["matrix"] = [[sum(1 for i in shared if t["A"][i] == r_ and t["B"][i] == s_) for s_ in TIERS] for r_ in TIERS]
    out["coder_vs_coder_tier"] = cc
    out["coder_vs_coder_questions"] = {}
    for q in QS:
        qa, qb = [a["A"][i][q] for i in shared], [a["B"][i][q] for i in shared]
        out["coder_vs_coder_questions"][q] = {**ag.compare(qa, qb, ORDER[q], False, DRAWS),
                                              "answers_A": dict(Counter(qa)), "answers_B": dict(Counter(qb))}
    # sensitivity
    sens = {}
    for c in "AB":
        have = [i for i in ids if i in t[c]]
        y = [levels[i]["level"] for i in have]
        per = {}
        for q in QS:
            held = [rule.tier_from_codes({**a[c][i], q: ORDER[q][0]}) for i in have]
            n_ans = len(ORDER[q])
            alone = [1 + round(ORDER[q].index(a[c][i][q]) * 3 / (n_ans - 1) - 0.01) for i in have]
            per[q] = {"held_least_risky_exact": sum(p == r for p, r in zip(held, y)),
                      "held_least_risky_kappa": ag.kappa(held, y, TIERS, True),
                      "alone_exact": sum(p == r for p, r in zip(alone, y)), "alone_kappa": ag.kappa(alone, y, TIERS, True)}
        sens[c] = per
    out["sensitivity"] = sens
    held_q2 = {}
    for c in "AB":
        have = [i for i in ids if i in t[c]]
        held = [rule.tier_from_codes({**a[c][i], "affects": "internal"}) for i in have]
        y = [levels[i]["level"] for i in have]
        held_q2[c] = {**ag.compare(held, y, TIERS, True, DRAWS), "tier_distribution": {str(k): held.count(k) for k in TIERS},
                      "within_one": sum(abs(p - r) <= 1 for p, r in zip(held, y)),
                      "above": sum(p > r for p, r in zip(held, y)), "below": sum(p < r for p, r in zip(held, y))}
    out["held_who_it_affects"] = held_q2
    # decided after seeing the results, labelled on the page: the same what-if on the other half of tier 3, at the answer that keeps cases alive
    held_sorts = {}
    for c in "AB":
        have = [i for i in ids if i in t[c]]
        held = [rule.tier_from_codes({**a[c][i], "decides": "sorts"}) for i in have]
        y = [levels[i]["level"] for i in have]
        held_sorts[c] = {**ag.compare(held, y, TIERS, True, DRAWS), "tier_distribution": {str(k): held.count(k) for k in TIERS},
                         "within_one": sum(abs(p - r) <= 1 for p, r in zip(held, y)),
                         "above": sum(p > r for p, r in zip(held, y)), "below": sum(p < r for p, r in zip(held, y))}
    out["after_results_held_decides_at_sorts"] = held_sorts
    # decided after seeing the results (second review), labelled on the page: which part of the tier 3 line put each tier 3 case there,
    # read in the line's own order, so a case is counted under the first part that fits
    def tier_three_part(x):
        stakes, sensitive = x["affects"] == "stakes", x["data"] == "sensitive"
        if stakes and x["decides"] == "decides":
            return "stakes_and_decides"
        if stakes and x["decides"] == "recommends" and x["review"] != "each":
            return "stakes_recommends_not_every_output_reviewed"
        if stakes and x["decides"] == "recommends" and sensitive:
            return "stakes_recommends_every_output_reviewed_sensitive"
        return "decides_unreviewed_sensitive"
    parts = {}
    for c in "AB":
        three = [i for i in ids if t[c].get(i) == 3]
        assert all(rule.tier_from_codes({**a[c][i], "affects": "internal"}) != 3 or tier_three_part(a[c][i]) == "decides_unreviewed_sensitive" for i in three)
        parts[c] = {"tier_3": len(three), **{k: sum(tier_three_part(a[c][i]) == k for i in three) for k in (
            "stakes_and_decides", "stakes_recommends_not_every_output_reviewed", "stakes_recommends_every_output_reviewed_sensitive", "decides_unreviewed_sensitive")}}
    out["after_results_tier_three_parts"] = parts
    # decided after seeing the results, labelled on the page: the paired test on the same cases, and whether order survives the offset
    pairs = {}
    for c in "AB":
        have = [i for i in ids if i in t[c]]
        base = {i: levels[i]["level"] == modal for i in have}
        versions = {"rule": t[c], "held_who_it_affects": {i: rule.tier_from_codes({**a[c][i], "affects": "internal"}) for i in have},
                    "held_decides_at_sorts": {i: rule.tier_from_codes({**a[c][i], "decides": "sorts"}) for i in have}}
        pairs[c] = {}
        for name, tiers_ in versions.items():
            mine = {i: tiers_[i] == levels[i]["level"] for i in have}
            only_mine, only_base = sum(mine[i] and not base[i] for i in have), sum(base[i] and not mine[i] for i in have)
            pairs[c][name] = {"only_this_right": only_mine, "only_baseline_right": only_base, "both_right": sum(mine[i] and base[i] for i in have),
                              "exact_mcnemar_p": ag.mcnemar_exact(only_mine, only_base)}
    out["after_results_paired_with_baseline"] = pairs
    order = {}
    for c in "AB":
        have = [i for i in ids if i in t[c]]
        x, y = [t[c][i] for i in have], [levels[i]["level"] for i in have]
        lo, hi, undefined = ag.superiority_bootstrap(x, y, 1, 2, DRAWS)
        order[c] = {"level_two_above_level_one": ag.superiority([p for p, r in zip(x, y) if r == 2], [p for p, r in zip(x, y) if r == 1]),
                    "ci": [lo, hi], "undefined_draws": undefined}
    out["after_results_order"] = order
    # decided after seeing the results, labelled on the page: the form's own answers, read from the documents by tools/form_answers.py
    form = json.loads((ROOT / "results" / "form_answers.json").read_text(encoding="utf-8"))
    frows = {r["case_id"]: r for r in form["rows"]}
    asked = [i for i in ids if frows[i]["stakes"]]
    out["after_results_form_answers"] = {
        "stakes_question": form["stakes_question"], "reversible_question": form["reversible_question"], "stakes_asked": len(asked),
        "stakes_by_answer_and_level": {v: {str(k): sum(frows[i]["stakes"] == v and levels[i]["level"] == k for i in ids) for k in (1, 2)} for v in ("Yes", "No")},
        "stakes_answer_also_coded_stakes": {c: {v: sum(frows[i]["stakes"] == v and a[c][i]["affects"] == "stakes" for i in ids) for v in ("Yes", "No")} for c in "AB"},
        "stakes_answer_visible_to_coders": sum(frows[i]["stakes_visible_after_redaction"] for i in asked),
        "reversible_answers": dict(Counter(frows[i]["reversible"] for i in ids)),
        "reversible_answer_visible_to_coders": sum(frows[i]["reversible_visible_after_redaction"] for i in ids),
        "impact_lines_removed": sum(frows[i]["impact_lines"] for i in ids), "impact_lines_little_to_no": sum(frows[i]["impact_little_to_no"] for i in ids),
        "documents_with_impact_lines": sum(frows[i]["impact_lines"] > 0 for i in ids),
        "impact_lines_with_reasoning": sum(frows[i]["impact_lines_with_reasoning"] for i in ids),
        "documents_with_reasoning_removed": sum(frows[i]["impact_lines_with_reasoning"] > 0 for i in ids),
        "impact_lines_left_after_redaction": sum(frows[i]["impact_lines_after_redaction"] for i in ids)}
    # decided after seeing the results, labelled as such on the page: share at Level II within each tier
    out["after_results_level_two_share"] = {c: {str(k): [sum(1 for i in ids if t[c].get(i) == k and levels[i]["level"] == 2),
                                                         sum(1 for i in ids if t[c].get(i) == k)] for k in TIERS} for c in "AB"}
    out["scores"] = {"highest_current": max(levels[i]["current_score"] for i in ids),
                     "current_below_raw": sum(levels[i]["raw_score"] is not None and levels[i]["current_score"] < levels[i]["raw_score"] for i in ids),
                     "with_raw_score": sum(levels[i]["raw_score"] is not None for i in ids),
                     "band_differs_on_current_maximum": sum(pct_band(levels[i]["current_score"]) != levels[i]["level"] for i in ids)}
    # disagreements
    rows_out = []
    for i in ids:
        lev = levels[i]["level"]
        row = {"case_id": i, "title": title[i], "level": lev, "current_score": levels[i]["current_score"],
               "raw_score": levels[i]["raw_score"], "mitigation_score": levels[i]["mitigation_score"],
               "edge_points": edge_distance(levels[i]["current_score"]), "band_on_current_maximum": pct_band(levels[i]["current_score"]),
               "coder_split": t["A"].get(i) != t["B"].get(i)}
        for c in "AB":
            if i in t[c]:
                r = codes[(c, i, 1)]["codes"]
                row[c] = {"tier": t[c][i], "answers": a[c][i], "direction": r["direction"], "measured": r["measured"]["answer"],
                          "outside": r["outside"]["answer"], "saw_overall": r["saw_overall"],
                          "unstated": [q for q in QS if not r[q]["stated"]],
                          "single_changes": single_changes(a[c][i], lev) if t[c][i] != lev else []}
        rows_out.append(row)
    out["case_rows"] = rows_out
    tally = {}
    for c in "AB":
        dis = [r for r in rows_out if c in r and r[c]["tier"] != r["level"]]
        moved = Counter(ch["question"] for r in dis for ch in r[c]["single_changes"])
        closes = Counter(q for r in dis for q in {ch["question"] for ch in r[c]["single_changes"]})
        tally[c] = {"disagreements": len(dis), "coder_split": sum(r["coder_split"] for r in dis),
                    "near_edge": sum(r["edge_points"] is not None and r["edge_points"] <= 5 for r in dis),
                    "with_unstated": sum(bool(r[c]["unstated"]) for r in dis),
                    "favourable_only": sum(r[c]["direction"] == "favourable_only" for r in dis),
                    "no_single_change": sum(not r[c]["single_changes"] for r in dis),
                    "questions_that_could_close_the_gap": dict(moved), "cases_one_question_could_close": dict(closes),
                    "near_edge_note": "Counted on today's maximum of 169, which does not fit every version of the tool, so the page reports no near-edge count."}
    out["disagreement_tally"] = tally
    # blinding, blind spots, stated
    out["blinding"] = {c: {"saw_overall_yes": sum(codes[(c, i, 1)]["codes"]["saw_overall"] == "yes" for i in ids if i in t[c]),
                           "yes_cases": [i for i in ids if i in t[c] and codes[(c, i, 1)]["codes"]["saw_overall"] == "yes"]} for c in "AB"}
    out["measured"] = {c: sum(codes[(c, i, 1)]["codes"]["measured"]["answer"] == "yes" for i in ids if i in t[c]) for c in "AB"}
    out["outside"] = {c: sum(codes[(c, i, 1)]["codes"]["outside"]["answer"] == "yes" for i in ids if i in t[c]) for c in "AB"}
    out["measured_both"] = sum(codes[("A", i, 1)]["codes"]["measured"]["answer"] == "yes" and codes[("B", i, 1)]["codes"]["measured"]["answer"] == "yes" for i in shared)
    out["measured_neither"] = sum(codes[("A", i, 1)]["codes"]["measured"]["answer"] == "no" and codes[("B", i, 1)]["codes"]["measured"]["answer"] == "no" for i in shared)
    out["outside_both"] = sum(codes[("A", i, 1)]["codes"]["outside"]["answer"] == "yes" and codes[("B", i, 1)]["codes"]["outside"]["answer"] == "yes" for i in shared)
    out["outside_neither"] = sum(codes[("A", i, 1)]["codes"]["outside"]["answer"] == "no" and codes[("B", i, 1)]["codes"]["outside"]["answer"] == "no" for i in shared)
    out["unstated"] = {c: {q: sum(not codes[(c, i, 1)]["codes"][q]["stated"] for i in ids if i in t[c]) for q in QS} for c in "AB"}
    # controls
    cmap = cases["control_ids"]
    out["controls"] = {}
    for c in "AB":
        rows_c = []
        for k in controls:
            r = codes.get((c, cmap[k["control_id"]], 1))
            if r:
                rows_c.append({"control": k["control_id"], "expected_tier": k["expected_tier"], "tier": tier_of(r),
                               "exact_answers": sum(answers(r)[q] == k["expected"][q] for q in QS)})
        out["controls"][c] = {"tier_correct": sum(x["tier"] == x["expected_tier"] for x in rows_c), "of": len(rows_c),
                              "answers_correct": sum(x["exact_answers"] for x in rows_c), "answers_of": 4 * len(rows_c), "rows": rows_c}
    out["retried_calls"] = {c: sum(int(codes[(c, i, run)].get("attempts", 1)) > 1 for i in [*ids, *cmap.values()] for run in (1, 2) if (c, i, run) in codes) for c in "AB"}
    # stability
    out["repeat"] = {}
    for c in "AB":
        again = [i for i in ids if (c, i, 2) in codes]
        out["repeat"][c] = {"cases": len(again), "same_tier": sum(tier_of(codes[(c, i, 1)]) == tier_of(codes[(c, i, 2)]) for i in again),
                            "same_answers": sum(answers(codes[(c, i, 1)])[q] == answers(codes[(c, i, 2)])[q] for i in again for q in QS),
                            "answers_of": 4 * len(again), "changed": [i for i in again if tier_of(codes[(c, i, 1)]) != tier_of(codes[(c, i, 2)])]}
    # money, on declared assumptions
    asm = json.loads((ROOT / "assumptions.json").read_text(encoding="utf-8"))
    hours = {int(k): v for k, v in asm["review_hours_by_tier"].items()}
    bill = lambda share: sum(asm["uses_per_year"] * share.get(k, 0) / len(ids) * hours[k] for k in TIERS) * asm["hourly_cost_usd"]
    out["money"] = {"published_levels_usd": bill(dist), **{f"rule_coder_{c}_usd": bill(Counter(t[c].values())) for c in "AB"},
                    **{f"rule_held_who_it_affects_coder_{c}_usd": bill({int(k): v for k, v in held_q2[c]["tier_distribution"].items()}) for c in "AB"}}
    # added after seeing the results, labelled on the page: the money gap with tier 3 review hours moved, the input it depends on most
    sweep = {}
    for h3 in (30, 60, 90):
        hrs = {**hours, 3: h3}
        one = lambda share: sum(asm["uses_per_year"] * share.get(k, 0) / len(ids) * hrs[k] for k in TIERS) * asm["hourly_cost_usd"]
        sweep[str(h3)] = {c: one(Counter(t[c].values())) - one({int(k): v for k, v in held_q2[c]["tier_distribution"].items()}) for c in "AB"}
    out["money"]["gap_removing_who_it_affects_by_tier_3_hours_usd"] = sweep
    # added after seeing the results, labelled on the page: every other assumed input, one at a time, and the other what-if
    held_dist = {c: {int(k): v for k, v in held_q2[c]["tier_distribution"].items()} for c in "AB"}
    sorts_dist = {c: {int(k): v for k, v in held_sorts[c]["tier_distribution"].items()} for c in "AB"}

    def gap(c, uses=asm["uses_per_year"], rate=asm["hourly_cost_usd"], over=None):
        hrs = {**hours, **(over or {})}
        one = lambda share: sum(uses * share.get(k, 0) / len(ids) * hrs[k] for k in TIERS) * rate
        return one(Counter(t[c].values())) - one(held_dist[c])
    out["money"]["gap_removing_who_it_affects_sweep_usd"] = {
        "base": {c: gap(c) for c in "AB"},
        "uses_per_year": {str(v): {c: gap(c, uses=v) for c in "AB"} for v in (10, 40)},
        "hourly_cost_usd": {str(v): {c: gap(c, rate=v) for c in "AB"} for v in (60, 120)},
        "tier_2_hours": {str(v): {c: gap(c, over={2: v}) for c in "AB"} for v in (8, 32)},
        "tier_4_hours": {str(v): {c: gap(c, over={4: v}) for c in "AB"} for v in (60, 240)}}
    out["money"].update({f"rule_held_decides_at_sorts_coder_{c}_usd": bill(sorts_dist[c]) for c in "AB"})
    # predictions
    q = out["coder_vs_coder_questions"]
    rv = out["rule_vs_level"]
    bs = json.loads((ROOT / "results" / "blind_spots.json").read_text(encoding="utf-8"))
    low_q = min(QS, key=lambda k: q[k]["exact_pct"])
    held = {
        "P1": (dist[1] + dist[2]) / len(ids) >= 0.75 and dist.get(4, 0) <= 2,
        "P2": all(30 <= rv[c]["exact_pct"] <= 60 for c in "AB"),
        "P3": all(100 * rv[c]["within_one"] / rv[c]["n"] >= 85 for c in "AB"),
        "P4": all(rv[c]["above"] >= 2 * rv[c]["below"] for c in "AB"),
        "P5": cc["exact_pct"] >= 65,
        "P6": all((rv[c]["kappa"] or 0) < (cc["kappa"] or 0) for c in "AB"),
        "P7": low_q == "review",
        "P8": all(100 * out["measured"][c] / out["coded"][c] < 25 for c in "AB"),
        "P9": len(bs["questions_matching_measured_pattern"]) <= 1,
        "P10": all(rv[c]["exact_pct"] - out["baseline"]["exact_pct"] <= 10 for c in "AB"),
        "P11": all(out["controls"][c]["tier_correct"] >= 5 for c in "AB"),
    }
    out["predictions"] = {k: ("held" if v else "missed") for k, v in held.items()}
    out["lowest_agreement_question"] = low_q
    # worked example, by the rule fixed in advance
    pool = [r for r in rows_out if not r["coder_split"] and "A" in r and "B" in r] or [r for r in rows_out if "A" in r]
    pick = sorted(pool, key=lambda r: (-abs(r["A"]["tier"] - r["level"]), r["case_id"]))[0]
    out["worked_example"] = pick["case_id"]
    (ROOT / "results" / "summary.json").write_text(json.dumps(out, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print(f"cases {len(ids)} coded {out['coded']} levels {out['level_distribution']}")
    print("VERDICT: PASS")


if __name__ == "__main__":
    main()
