"""Registered positive-pole pairs (plan2/analysis-plan.md); same measure as code/pairs.py.
A pair is supported only if its percentile is at least 0.95 AND at least MIN_HIT_FAMILIES
families colexify it. Writes the given output JSON. Usage: python code/pairs2.py <forms> <languages> <out.json>
"""
import json
import sys

import numpy as np

sys.path.insert(0, "code")
import colex  # noqa: E402

PAIRS = [("UP", "HAPPY"), ("HIGH", "HAPPY"), ("LIGHT (WEIGHT)", "EASY"), ("LIGHT (WEIGHT)", "HAPPY"),
         ("SOFT", "QUIET"), ("SOFT", "GENTLE"), ("STRAIGHT", "GOOD"), ("HEAVY", "DIFFICULT")]
MIRRORS = {"UP|HAPPY": "DOWN|SAD", "HIGH|HAPPY": "LOW|SAD", "LIGHT (WEIGHT)|EASY": "HEAVY|DIFFICULT",
           "LIGHT (WEIGHT)|HAPPY": "HEAVY|SAD", "SOFT|QUIET": "HARD|ANGRY", "STRAIGHT|GOOD": "CROOKED|BAD"}
MIN_FAMILIES = 30
MIN_HIT_FAMILIES = 3


def evaluate(pairs, lex, fam):
    out = {}
    for anchor in sorted({a for a, _ in pairs}):
        rates = colex.rates_for(anchor, lex, fam)
        targets = {t for a, t in pairs if a == anchor}
        ref = [k / n for c, (k, n) in rates.items() if n >= MIN_FAMILIES and c not in targets]
        for t in targets:
            k, n = rates.get(t, (0, 0))
            rec = {"families_colexifying": k, "families_with_both": n, "rate": round(k / n, 4) if n else None}
            if n >= MIN_FAMILIES and ref:
                pct = colex.percentile_of(k / n, ref)
                rec.update({"percentile": round(pct, 4), "supported": bool(pct >= 0.95 and k >= MIN_HIT_FAMILIES)})
            else:
                rec.update({"percentile": None, "supported": None})
            out[f"{anchor}|{t}"] = rec
    return out


def main():
    lex, fam = colex.load(sys.argv[1], sys.argv[2])
    res = {"pairs": evaluate(PAIRS, lex, fam)}
    neg = evaluate([tuple(v.split("|")) for v in MIRRORS.values() if v != "HEAVY|DIFFICULT"], lex, fam)
    neg["HEAVY|DIFFICULT"] = res["pairs"]["HEAVY|DIFFICULT"]
    res["mirror_comparison"] = {p: {"positive": res["pairs"][p], "negative": neg[m]} for p, m in MIRRORS.items()}
    with open(sys.argv[3], "w") as fh:
        json.dump(res, fh, indent=2, sort_keys=True, ensure_ascii=False)
        fh.write("\n")
    print(json.dumps(res, indent=1, ensure_ascii=False))


if __name__ == "__main__":
    main()
