"""Post hoc sensitivity for the registered screen (added in the corrected version, after review).

Reads results/R1.json written by code/mechanics.py and reports, for each class:
- how many counted anchor-target pairs were possible and how many met the coverage rule;
- how many eligible pairs had any colexifying family;
- the pairs that would be hits at a two-family threshold (percentile >= 0.95, >= 2 families);
- the chance of zero hits for a random concept set of the class's size, from the pool's
  share of concepts with any hit (treating anchors as independent).

Usage: python code/sensitivity.py results/R1.json results/R2.json
"""
import json
import sys

sys.path.insert(0, "code")
from mechanics import CLASSES, COUNTED  # noqa: E402

r1 = json.load(open(sys.argv[1]))
share = r1["pool"]["share_with_any_hit"]
out = {"pool_share_with_any_hit": share, "classes": {}, "two_family_hits": []}
for cl, anchors in CLASSES.items():
    possible = len(anchors) * len(COUNTED)
    eligible = some = 0
    for a in anchors:
        for t, p in r1["pairs"].get(a, {}).items():
            if t not in COUNTED:
                continue
            eligible += 1
            some += p["families_colexifying"] >= 1
            if p["percentile"] >= 0.95 and p["families_colexifying"] >= 2:
                out["two_family_hits"].append({"class": cl, "anchor": a, "target": t,
                                               "families": p["families_colexifying"],
                                               "of": p["families_with_both"], "percentile": p["percentile"]})
    two = sum(h["class"] == cl for h in out["two_family_hits"])
    out["classes"][cl] = {"possible_pairs": possible, "eligible_pairs": eligible,
                          "eligible_with_any_colexification": some, "two_family_hits": two,
                          "p_zero_hits_random_set": round((1 - share) ** len(anchors), 3)}
nonload = [c for c in CLASSES if c != "load"]
out["nonload"] = {k: sum(out["classes"][c][k] for c in nonload)
                  for k in ("possible_pairs", "eligible_pairs", "eligible_with_any_colexification", "two_family_hits")}
p_all = 1.0
for c in nonload:
    p_all *= out["classes"][c]["p_zero_hits_random_set"]
out["nonload"]["p_all_four_zero_random"] = round(p_all, 3)
json.dump(out, open(sys.argv[2], "w"), indent=1)
