"""Summarize the stored runs into results/summary-r1.json and score the predictions as declared.

Usage: python3 -I -B tools/summarize.py
"""
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
RES = ROOT / "results"
CHECKS = ["totals", "totals_by_status", "target_rules", "code_census", "record_compare", "cheap_set"]
SBA = ("7A", "504")


def load(name):
    return json.loads((RES / name).read_text(encoding="utf-8"))


def share(faults, check, layer=None):
    fs = [f for f in faults if layer is None or f["layer"] == layer]
    n = sum(1 for f in fs if f["fired"][check])
    return {"caught": n, "of": len(fs), "share": n / len(fs) if fs else None}


def chargeoff_moves(f, correct):
    """Does the fault change a charge-off figure a credit team reads (amount or rate, either SBA program)?"""
    out = {}
    for s in SBA:
        a, b = f["stakes"].get(s), correct[s]
        if a is None:
            out[s] = {"chargeoff_reported_usd": -b["chargeoff_reported_usd"], "rate_count": None, "rate_principal": None}
            continue
        out[s] = {"chargeoff_reported_usd": round(a["chargeoff_reported_usd"] - b["chargeoff_reported_usd"], 2),
                  "rate_count": a["chargeoff_rate_count"], "rate_principal": a["chargeoff_rate_principal"],
                  "rate_count_correct": b["chargeoff_rate_count"], "rate_principal_correct": b["chargeoff_rate_principal"]}
    moved = any(abs(v["chargeoff_reported_usd"]) > 1.0 or
                (v.get("rate_count") is not None and abs(v["rate_count"] - v["rate_count_correct"]) > 1e-9) or
                (v.get("rate_principal") is not None and abs(v["rate_principal"] - v["rate_principal_correct"]) > 1e-9) or
                v.get("rate_count") is None for v in out.values())
    return moved, out


def per_fault(f, correct):
    moved, co = chargeoff_moves(f, correct)
    return {"id": f["id"], "layer": f["layer"], "name": f["name"], "family": f.get("family"),
            "dictionary": f.get("dictionary", False), "fired": f["fired"],
            "affected": f["effect"]["affected"], "affected_by_source": f["effect"]["by_source"],
            "principal_affected_usd": f["effect"]["principal_affected_usd"],
            "p_sample_60": f["sample_60"]["p_catch"], "p_sample_200": f["sample_200"]["p_catch"],
            "rules_moved": f["target_rules"].get("moved", {}), "totals_diffs": f["totals"]["diffs"],
            "census_unmapped": f["code_census"]["unmapped"], "chargeoff_moves": moved, "chargeoff": co,
            "hmda_originations": (f["stakes"].get("HMDA") or {}).get("hmda_originations")}


def main():
    prep, main_r, fresh_r = load("prepare-r1.json"), load("main-r1.json"), load("fresh-r1.json")
    pred = json.loads((ROOT / "predictions-r1.json").read_text(encoding="utf-8"))
    correct = prep["stakes_correct"]
    M = [per_fault(f, correct) for f in main_r["faults"]]
    F = [per_fault(f, correct) for f in fresh_r["faults"]]
    table = {}
    for c in CHECKS:
        table[c] = {"main": share(M, c), "main_code": share(M, c, "code"), "main_rule": share(M, c, "rule"),
                    "fresh": share(F, c), "fresh_code": share(F, c, "code"), "fresh_rule": share(F, c, "rule")}
    for n in (60, 200):
        k = f"p_sample_{n}"
        table[f"sample_{n}"] = {
            "main_expected": sum(f[k] for f in M), "main_below_half": [f["id"] for f in M if f[k] < 0.5],
            "fresh_expected": sum(f[k] for f in F), "fresh_below_half": [f["id"] for f in F if f[k] < 0.5],
            "main_seeded": sum(1 for f in M if f["fired"][f"sample_{n}_seeded"]),
            "fresh_seeded": sum(1 for f in F if f["fired"][f"sample_{n}_seeded"])}
    combos = {}
    for name, members in (("cheap_set_plus_record_compare", ("cheap_set", "record_compare")),
                          ("every_automated_check", ("totals", "totals_by_status", "target_rules", "code_census", "record_compare"))):
        row = {}
        for label, fs in (("main", M), ("fresh", F)):
            caught = [f for f in fs if any(f["fired"][m] for m in members)]
            left = [f for f in fs if f not in caught]
            row[label] = {"caught": len(caught), "of": len(fs), "missed": [f["id"] for f in left],
                          "plus_sample_60_expected": len(caught) + sum(f["p_sample_60"] for f in left)}
        combos[name] = row
    fired = {f["id"]: f["fired"] for f in M}
    code_ids = [f["id"] for f in M if f["layer"] == "code"]
    rule_ids = [f["id"] for f in M if f["layer"] == "rule"]
    tot_miss = [i for i in fired if not fired[i]["totals"]]
    scored = {
        "P1": {"value": len(tot_miss), "held": len(tot_miss) >= 9},
        "P2": {"value": [fired["M18"]["totals"], fired["M19"]["totals"]], "held": not fired["M18"]["totals"] and not fired["M19"]["totals"]},
        "P3": {"value": [sum(fired[i]["record_compare"] for i in code_ids), sum(fired[i]["record_compare"] for i in rule_ids)],
               "held": all(fired[i]["record_compare"] for i in code_ids) and not any(fired[i]["record_compare"] for i in rule_ids)},
        "P4": {"value": sum(fired[i]["target_rules"] for i in rule_ids), "held": sum(fired[i]["target_rules"] for i in rule_ids) >= 4},
        "P5": {"value": sum(1 for i in tot_miss if fired[i]["totals_by_status"]),
               "held": sum(1 for i in tot_miss if fired[i]["totals_by_status"]) <= 2},
        "P6": {"value": len(table["sample_60"]["main_below_half"]), "held": len(table["sample_60"]["main_below_half"]) >= 3},
        "P7": {"value": table["cheap_set"]["main"]["caught"], "held": table["cheap_set"]["main"]["caught"] >= 15},
    }
    gaps = {c: abs(table[c]["fresh"]["share"] - table[c]["main"]["share"]) for c in ("totals", "target_rules", "cheap_set")}
    scored["P8"] = {"value": {c: round(g * 100, 1) for c, g in gaps.items()}, "held": all(g <= 0.15 for g in gaps.values())}
    co_fresh = [f for f in F if f["chargeoff_moves"]]
    co_missed = [f["id"] for f in co_fresh if not f["fired"]["cheap_set"]]
    reversal = {
        "totals_alone_fresh_share": table["totals"]["fresh"]["share"],
        "totals_alone_enough": table["totals"]["fresh"]["share"] >= 0.8,
        "fresh_chargeoff_faults": [f["id"] for f in co_fresh],
        "fresh_chargeoff_missed_by_cheap_set": co_missed,
        "cheap_set_miss_share_on_chargeoff_faults": (len(co_missed) / len(co_fresh)) if co_fresh else None,
        "add_record_compare_to_gate": (len(co_missed) / len(co_fresh) > 0.10) if co_fresh else None,
    }
    co_main = [f for f in M if f["chargeoff_moves"]]
    out = {"checks": table, "combinations": combos, "predictions_scored": scored, "prediction_text": {p["id"]: p["text"] for p in pred["predictions"]},
           "reversal": reversal, "main_chargeoff_faults": [f["id"] for f in co_main],
           "main_chargeoff_missed_by_totals": [f["id"] for f in co_main if not f["fired"]["totals"]],
           "main_chargeoff_missed_by_cheap_set": [f["id"] for f in co_main if not f["fired"]["cheap_set"]],
           "fresh_draws": fresh_r["draws"], "fresh_redraws": fresh_r["redraws"],
           "fresh_identical_pairs": [[a["id"], b["id"]] for i, a in enumerate(F) for b in F[i + 1:] if a["name"] == b["name"]],
           "correct": {"stakes": correct, "rule_failures": prep["clean_checks"]["target_rules"]["counts"],
                       "by_source": prep["by_source"], "exact_duplicates": prep["exact_duplicates"],
                       "status": prep["status"], "census_with_dictionary_maps": prep["census_with_dictionary_maps"]},
           "main": M, "fresh": F}
    (RES / "summary-r1.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    for c in CHECKS + ["sample_60", "sample_200"]:
        print(c, json.dumps(table[c]))
    print("predictions:", {k: v["held"] for k, v in scored.items()}, scored["P8"]["value"])
    print("reversal:", json.dumps(reversal))
    print("main charge-off faults:", out["main_chargeoff_faults"], "missed by totals:", out["main_chargeoff_missed_by_totals"],
          "missed by cheap:", out["main_chargeoff_missed_by_cheap_set"])
    print("identical fresh pairs:", out["fresh_identical_pairs"])
    print("combinations:", json.dumps(combos))


if __name__ == "__main__":
    main()
