"""The validation run declared in DESIGN.md Part 2. Writes results/results.json.

    python -m cmv.validate <archive> [cache dir]

Every out-of-sample number comes from the validation partition. The development partition is used only to refit the
report's own procedure and the challengers. Grades follow the rules in DESIGN.md and are computed here, not typed.
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedGroupKFold, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from . import metrics as M
from .data import BILL, PAID, PAY, TARGET, load, split
from .developer import freeze_record, load_frozen

ROOT = Path(__file__).resolve().parents[1]
FIN = ["LIMIT_BAL"] + PAY + BILL + PAID  # the developer's 19 inputs
TRAITS = ["SEX", "AGE", "EDUCATION", "MARRIAGE"]
CUT = 0.20
COST_DEFAULT, COST_GOOD = 2000.0, 500.0
BOOT, BOOT_SEED, HALF_SEED = 1000, 7, 11
GRID = np.round(np.arange(0.05, 0.6001, 0.005), 3)
BANDS = [0.0, 0.10, 0.15, 0.20, 0.25, 0.35, 0.50, 1.0]
RATIOS = [2, 3, 4, 6, 8]


def r6(x):
    return None if x is None else round(float(x), 6)


def est(point, boots):
    lo, hi = M.interval(boots)
    return {"point": r6(point), "lo": r6(lo), "hi": r6(hi)}


def stale(df: pd.DataFrame) -> pd.DataFrame:
    """The same holders as if the file were a month old: each monthly column takes the previous month's value."""
    out = df.copy()
    for cols in (PAY, BILL, PAID):
        vals = df[cols].to_numpy()
        out[cols] = np.column_stack([vals[:, 1:], vals[:, -1:]])
    return out


def policy(y, s, w, cut):
    """Approval at score < cut: approval rate, default rate among approved, shares, unit and US$ costs."""
    a = s < cut
    W = w.sum()
    app, app_bad = (w * a).sum(), (w * a * (y == 1)).sum()
    bad, good = (w * (y == 1)).sum(), (w * (y == 0)).sum()
    dec_good = (w * ~a * (y == 0)).sum()
    return {"approval": app / W, "default_approved": app_bad / app if app else np.nan,
            "defaulters_declined": 1 - app_bad / bad, "goods_approved": 1 - dec_good / good,
            "unit_cost": (4 * app_bad + dec_good) / W,
            "usd_per_1000": (COST_DEFAULT * app_bad + COST_GOOD * dec_good) / W * 1000}


def usd_cost(y, s, w, cut, ratio=4.0):
    a = s < cut
    good_cost = COST_DEFAULT / ratio
    return float((COST_DEFAULT * (w * a * (y == 1)).sum() + good_cost * (w * ~a * (y == 0)).sum()) / w.sum() * 1000)


def shuffle_change(score_fn, df: pd.DataFrame, cols: list[str], seed: int = 0) -> float:
    """Largest change in any score when the named columns are shuffled across rows (0 means the scores ignore them)."""
    shuf = df.copy()
    rng = np.random.default_rng(seed)
    for c in cols:
        shuf[c] = rng.permutation(shuf[c].to_numpy())
    return float(np.abs(score_fn(shuf) - score_fn(df)).max())


def boot_metric(fn, counts, base_w=None):
    return np.array([fn(c if base_w is None else c * base_w) for c in counts])


def verdict(claim, lo, hi, better):
    """better: 'higher', 'lower' or 'none' (two-sided)."""
    if lo <= claim <= hi:
        return "holds"
    if better == "none":
        return "differs"
    worse = (hi < claim) if better == "higher" else (lo > claim)
    return "weaker than claimed" if worse else "better than claimed"


def main(argv):
    archive = Path(argv[0])
    cache = Path(argv[1]) if len(argv) > 1 else ROOT / "cache"
    full = load(archive)
    dev, val = split(full)
    mod, model = load_frozen(cache, dev)
    y = val[TARGET].to_numpy()
    s = mod.score(model, val)
    n = len(val)
    one = np.ones(n)
    counts = M.boot_counts(n, BOOT, BOOT_SEED)
    s_dev = mod.score(model, dev)
    edges = M.psi_edges(s_dev)
    R: dict = {"schema": "credit-model-validation/1", "freeze": freeze_record(),
               "data": {"rows": len(full), "development_rows": len(dev), "validation_rows": n,
                        "validation_defaults": int(y.sum()), "validation_default_rate": r6(y.mean()),
                        "development_default_rate": r6(dev[TARGET].mean())}}

    # 1. intended use
    if list(mod._FEATURES) != FIN:
        raise RuntimeError("the frozen module's inputs are not the 19 listed here")
    hist = [c for c in FIN if c != "LIMIT_BAL"]
    R["use"] = {"inputs": FIN, "history_inputs": len(hist), "total_inputs": len(FIN), "months_of_history": 6}

    # 2. reproduction of the report from its own description
    groups = pd.util.hash_pandas_object(dev[FIN], index=False).to_numpy()
    yd = dev[TARGET].to_numpy()
    tr, te = next(StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=20261023).split(dev, yd, groups))
    m_rep = mod.fit(dev.iloc[tr])
    yt, st = yd[te], mod.score(m_rep, dev.iloc[te])
    wt = np.ones(len(te))
    pol = policy(yt, st, wt, CUT)
    q = pd.qcut(st, 5, labels=False)
    sex = dev.iloc[te]["SEX"].to_numpy()
    R["reproduction"] = {
        "test_rows": int(len(te)), "test_defaults": int(yt.sum()), "train_rows": int(len(tr)),
        "auc": r6(M.auc(yt, st)), "ap": r6(M.average_precision(yt, st)), "log_loss": r6(M.log_loss(yt, st)),
        "brier": r6(M.brier(yt, st)), "mean_pred": r6(st.mean()), "observed": r6(yt.mean()),
        "quintiles": [{"mean_pred": r6(st[q == k].mean()), "observed": r6(yt[q == k].mean())} for k in range(5)],
        "approve_good": int(((st < CUT) & (yt == 0)).sum()), "approve_bad": int(((st < CUT) & (yt == 1)).sum()),
        "decline_good": int(((st >= CUT) & (yt == 0)).sum()), "decline_bad": int(((st >= CUT) & (yt == 1)).sum()),
        **{k: r6(v) for k, v in pol.items() if k != "usd_per_1000"},
        "approve_all_cost": r6(4 * yt.mean()), "decline_all_cost": r6(1 - yt.mean()),
        "by_sex": {g: {"approval": r6((st[sex == c] < CUT).mean()),
                       "default_approved": r6(yt[(sex == c) & (st < CUT)].mean())} for g, c in (("male", 1), ("female", 2))}}

    # 3. discrimination on the validation partition
    disc = {}
    for name, fn in (("auc", M.auc), ("ap", M.average_precision), ("log_loss", M.log_loss), ("brier", M.brier), ("ks", M.ks)):
        disc[name] = est(fn(y, s), boot_metric(lambda w: fn(y, s, w), counts))
    R["discrimination"] = disc

    # 4. calibration
    qv = pd.qcut(s, 5, labels=False)
    quint = []
    for k in range(5):
        m = qv == k
        lo, hi = M.wilson(y[m].sum(), m.sum())
        quint.append({"rows": int(m.sum()), "mean_pred": r6(s[m].mean()), "observed": r6(y[m].mean()), "lo": r6(lo), "hi": r6(hi),
                      "miscalibrated": bool(not (lo <= s[m].mean() <= hi))})
    bands = []
    for a, b in zip(BANDS[:-1], BANDS[1:]):
        m = (s >= a) & ((s < b) if b < 1 else (s <= b))
        lo, hi = M.wilson(y[m].sum(), m.sum())
        bands.append({"from": a, "to": b, "rows": int(m.sum()), "mean_pred": r6(s[m].mean()), "observed": r6(y[m].mean()),
                      "lo": r6(lo), "hi": r6(hi), "miscalibrated": bool(not (lo <= s[m].mean() <= hi))})
    gap = lambda w: M.mean(y, w) - M.mean(s, w)  # noqa: E731
    R["calibration"] = {"quintiles": quint, "bands": bands,
                        "large": {"mean_pred": r6(s.mean()), "observed": r6(y.mean()), "gap": est(gap(one), boot_metric(gap, counts))}}

    # policy at the cutoff, validation partition
    pol_b = {k: [] for k in ("approval", "default_approved", "defaulters_declined", "goods_approved", "unit_cost", "usd_per_1000")}
    for c in counts:
        p = policy(y, s, c.astype(float), CUT)
        for k in pol_b:
            pol_b[k].append(p[k])
    p0 = policy(y, s, one, CUT)
    R["policy"] = {k: est(p0[k], pol_b[k]) for k in pol_b}
    R["policy"]["approve_all_cost"] = est(4 * y.mean(), boot_metric(lambda w: 4 * M.mean(y, w), counts))
    R["policy"]["decline_all_cost"] = est(1 - y.mean(), boot_metric(lambda w: 1 - M.mean(y, w), counts))

    # 5 and 6. stale feed and declared stresses
    s_stale = mod.score(model, stale(val))
    anydelay = (val[PAY].to_numpy() >= 1).any(axis=1)
    pops = [("S0", "As drawn", one, s), ("S1", "Aged 30 or under weighted 3", np.where(val["AGE"] <= 30, 3.0, 1.0), s),
            ("S2", "Credit limit of NT$50,000 or less weighted 3", np.where(val["LIMIT_BAL"] <= 50_000, 3.0, 1.0), s),
            ("S3", "Any payment delay in six months weighted 3", np.where(anydelay, 3.0, 1.0), s),
            ("S4", "Stale feed: every monthly column a month old", one, s_stale)]
    stress = []
    for sid, label, w, sc in pops:
        g = lambda c, w=w, sc=sc: M.mean(y, c * w) - M.mean(sc, c * w)  # noqa: E731
        pp = policy(y, sc, w, CUT)
        stress.append({"id": sid, "label": label, "psi": r6(M.psi(s_dev, sc, edges, w)),
                       "share_weighted_up": r6((w > 1).mean()) if sid in ("S1", "S2", "S3") else None,
                       "auc": est(M.auc(y, sc, w), boot_metric(lambda c, w=w, sc=sc: M.auc(y, sc, c * w), counts)),
                       "gap": est(g(np.ones(n)), [g(c) for c in counts]),
                       "approval": r6(pp["approval"]), "default_approved": r6(pp["default_approved"])})
    R["stress"] = stress
    d_stale = [M.auc(y, s, c) - M.auc(y, s_stale, c) for c in counts]
    R["stale"] = {"auc_drop": est(M.auc(y, s) - M.auc(y, s_stale), d_stale),
                  "mean_pred": r6(s_stale.mean()), "approval": r6(policy(y, s_stale, one, CUT)["approval"]),
                  "default_approved": r6(policy(y, s_stale, one, CUT)["default_approved"]),
                  "status_changed_share": r6((val["PAY_0"].to_numpy() != val["PAY_2"].to_numpy()).mean())}

    # 7. challengers
    lr = make_pipeline(StandardScaler(), LogisticRegression(C=1.0, max_iter=2000))
    lr.fit(dev[FIN].to_numpy(dtype=float), yd)
    s_lr = lr.predict_proba(val[FIN].to_numpy(dtype=float))[:, 1]
    s_p0 = val["PAY_0"].to_numpy(dtype=float)
    ch = {}
    for name, sc in (("logistic", s_lr), ("latest_status", s_p0)):
        ch[name] = {"auc": est(M.auc(y, sc), boot_metric(lambda c, sc=sc: M.auc(y, sc, c), counts)),
                    "model_minus": est(M.auc(y, s) - M.auc(y, sc), [M.auc(y, s, c) - M.auc(y, sc, c) for c in counts])}
    ch["logistic"]["log_loss"] = r6(M.log_loss(y, s_lr))
    rule = s_p0 <= 0
    rate = rule.mean()
    model_cut = np.quantile(s, rate)  # beyond the plan, not graded: the model at the rule's approval rate
    ma = s < model_cut
    ch["latest_status"]["rule"] = {"approval": r6(rate), "default_approved": r6(y[rule].mean()),
                                   "model_same_rate_approval": r6(ma.mean()), "model_same_rate_default_approved": r6(y[ma].mean())}
    R["challengers"] = ch

    # 8. protected traits
    age = val["AGE"].to_numpy()
    groups_def = {
        "sex": [("male", val["SEX"].to_numpy() == 1), ("female", val["SEX"].to_numpy() == 2)],
        "age": [("30 or under", age <= 30), ("31 to 40", (age > 30) & (age <= 40)), ("41 to 50", (age > 40) & (age <= 50)), ("over 50", age > 50)],
        "marital status": [("married", val["MARRIAGE"].to_numpy() == 1), ("single", val["MARRIAGE"].to_numpy() == 2),
                           ("other", np.isin(val["MARRIAGE"].to_numpy(), [0, 3]))],
        "education": [("graduate school", val["EDUCATION"].to_numpy() == 1), ("university", val["EDUCATION"].to_numpy() == 2),
                      ("high school", val["EDUCATION"].to_numpy() == 3), ("other", np.isin(val["EDUCATION"].to_numpy(), [0, 4, 5, 6]))],
    }
    traits = {}
    for trait, gs in groups_def.items():
        rows = []
        for gname, m in gs:
            a = m & (s < CUT)
            alo, ahi = M.wilson(a.sum(), m.sum())
            dlo, dhi = M.wilson(y[a].sum(), a.sum())
            olo, ohi = M.wilson(y[m].sum(), m.sum())
            mp = s[m].mean()
            rows.append({"group": gname, "rows": int(m.sum()), "approval": r6(a.mean() / m.mean()), "approval_lo": r6(alo), "approval_hi": r6(ahi),
                         "default_approved": r6(y[a].mean()), "default_approved_lo": r6(dlo), "default_approved_hi": r6(dhi),
                         "mean_pred": r6(mp), "observed": r6(y[m].mean()), "gap": r6(y[m].mean() - mp), "gap_lo": r6(olo - mp), "gap_hi": r6(ohi - mp)})
        top = max(r["approval"] for r in rows)
        for r in rows:
            r["ratio"] = r6(r["approval"] / top)
        traits[trait] = rows
    X = val[FIN].to_numpy(dtype=float)
    proxy = {}
    for name, t in (("female", val["SEX"].to_numpy() == 2), ("aged 30 or under", age <= 30),
                    ("single", val["MARRIAGE"].to_numpy() == 2), ("graduate school", val["EDUCATION"].to_numpy() == 1)):
        cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
        sc = cross_val_score(HistGradientBoostingClassifier(random_state=0), X, t.astype(int), cv=cv, scoring="roc_auc")
        proxy[name] = {"share": r6(t.mean()), "auc": r6(sc.mean()), "fold_min": r6(sc.min()), "fold_max": r6(sc.max())}
    R["traits"] = {"groups": traits, "proxy": proxy,
                   "shuffle_max_abs_change": r6(shuffle_change(lambda d: mod.score(model, d), val, ["ID"] + TRAITS))}

    # 9. decision
    perm = np.random.default_rng(HALF_SEED).permutation(n)
    halves = {"A": np.sort(perm[: n // 2]), "B": np.sort(perm[n // 2:])}
    hcounts = M.boot_counts(n // 2, BOOT, BOOT_SEED)
    decision = {"cost_default_usd": COST_DEFAULT, "cost_good_declined_usd": COST_GOOD, "sweep": []}
    for ratio in RATIOS:
        theo = round(1 / (1 + ratio), 6)
        entry = {"ratio": ratio, "good_declined_usd": r6(COST_DEFAULT / ratio), "calibrated_cutoff": theo, "halves": {}}
        for h, other in (("A", "B"), ("B", "A")):
            io, ie = halves[other], halves[h]
            costs = [usd_cost(y[io], s[io], np.ones(len(io)), c, ratio) for c in GRID]
            chosen = float(GRID[int(np.argmin(costs))])
            ye, se = y[ie], s[ie]
            base = usd_cost(ye, se, np.ones(len(ie)), theo, ratio)
            new = usd_cost(ye, se, np.ones(len(ie)), chosen, ratio)
            diffs = [usd_cost(ye, se, c.astype(float), theo, ratio) - usd_cost(ye, se, c.astype(float), chosen, ratio) for c in hcounts]
            entry["halves"][h] = {"chosen_cutoff": chosen, "cost_at_calibrated": r6(base), "cost_at_chosen": r6(new),
                                  "saving": est(base - new, diffs),
                                  "approval_at_calibrated": r6((se < theo).mean()), "approval_at_chosen": r6((se < chosen).mean()),
                                  "default_approved_at_chosen": r6(ye[se < chosen].mean())}
        hs = entry["halves"].values()
        entry["saving_mean"] = r6(np.mean([v["saving"]["point"] for v in hs]))
        entry["both_halves_clear"] = all(v["saving"]["lo"] > 0 for v in hs)
        decision["sweep"].append(entry)
    R["decision"] = decision

    # 10. data checks (all 30,000 rows; no outcome used except for conflicting duplicates)
    dup = full.duplicated(subset=FIN, keep="first")
    R["data_checks"] = {
        "education_undocumented": int(full["EDUCATION"].isin([0, 5, 6]).sum()),
        "marriage_undocumented": int((full["MARRIAGE"] == 0).sum()),
        "status_minus2_share": {c: r6((full[c] == -2).mean()) for c in PAY},
        "status_0_share": {c: r6((full[c] == 0).mean()) for c in PAY},
        "status_1_share": {c: r6((full[c] == 1).mean()) for c in PAY},
        "repeated_profiles_beyond_first": int(dup.sum()),
        "rows_with_negative_bill": int((full[BILL] < 0).any(axis=1).sum()),
    }

    R["findings"] = grade(R)

    # Added after the results were read (not graded): what the gaps to the report's claims are made of.
    rep_rate = R["reproduction"]["observed"]
    wb = np.where(y == 1, rep_rate / y.mean(), (1 - rep_rate) / (1 - y.mean()))
    pb = policy(y, s, wb, CUT)
    claimed_iv = {"auc": (0.7757, 0.8138), "ap": (0.5461, 0.6196), "log_loss": (0.3886, 0.4269), "brier": (0.1185, 0.1329),
                  "approval": (0.6570, 0.6950), "default_approved": (0.0899, 0.1139)}
    rows = {r["group"]: r for r in R["traits"]["groups"]["education"]}
    R["post_hoc"] = {
        "note": "Added after the validation results were read; not graded.",
        "reweighted_to_report_default_rate": {"default_rate": r6(rep_rate), "log_loss": r6(M.log_loss(y, s, wb)), "brier": r6(M.brier(y, s, wb)),
                                              "auc": r6(M.auc(y, s, wb)), "approval": r6(pb["approval"]), "default_approved": r6(pb["default_approved"])},
        "inside_claimed_interval": {k: bool(lo <= get(R, ("discrimination." if k in ("auc", "ap", "log_loss", "brier") else "policy.") + k)["point"] <= hi)
                                    for k, (lo, hi) in claimed_iv.items()},
        "claimed_interval": claimed_iv,
        "education_ratio_to_graduate_school": {g: r6(rows[g]["approval"] / rows["graduate school"]["approval"]) for g in ("university", "high school")},
    }
    R["predictions"] = predictions(R)
    out = ROOT / "results" / "results.json"
    out.parent.mkdir(exist_ok=True)
    tmp = out.with_suffix(".tmp")
    tmp.write_text(json.dumps(R, indent=1, allow_nan=False) + "\n", encoding="utf-8")
    tmp.replace(out)
    print(f"VERDICT: PASS (results written; {len(R['findings'])} findings)")
    return 0


# Claims from developer/REPORT.md: (id, the report's exact words, results path, claimed value, better direction)
CLAIMS = [
    ("auc", "ROC AUC was **0.7939**", "discrimination.auc", 0.7939, "higher"),
    ("ap", "average precision was **0.5835**", "discrimination.ap", 0.5835, "higher"),
    ("log_loss", "log loss was **0.4078**", "discrimination.log_loss", 0.4078, "lower"),
    ("brier", "| Brier score | 0.1260 |", "discrimination.brier", 0.1260, "lower"),
    ("approval", "Approval rate was **67.69%**", "policy.approval", 0.6769, "none"),
    ("default_approved", "Observed default among approved holders was **10.18%**", "policy.default_approved", 0.1018, "lower"),
    ("defaulters_declined", "The policy declined 67.84% of future defaulters", "policy.defaulters_declined", 0.6784, "higher"),
    ("goods_approved", "approved 77.38% of nondefaulters", "policy.goods_approved", 0.7738, "higher"),
    ("unit_cost", "observed cost was 0.4534 units per holder", "policy.unit_cost", 0.4534, "lower"),
]


def get(R, path):
    for k in path.split("."):
        R = R[k]
    return R


def grade(R) -> list[dict]:
    F = []
    report = (ROOT / "developer" / "REPORT.md").read_text(encoding="utf-8")

    def add(fid, grade_, rule, title, evidence):
        F.append({"id": fid, "grade": grade_, "rule": rule, "title": title, "evidence": evidence})

    u = R["use"]
    # B1 rests on two quotes, asserted here, not on a reader's judgement: the data dictionary describes 18 of the 19
    # inputs as the holder's own monthly history, and the report says its results do not cover applicants without it.
    dictionary = (ROOT / "author" / "DATA_DICTIONARY.md").read_text(encoding="utf-8")
    dict_words = ["History of past payment", "Amount of bill statement", "Amount of previous payment"]
    report_words = "They do not establish performance for applicants without such history"
    assert all(w in dictionary for w in dict_words) and report_words in report
    add("use", "blocks approval", "B1", "The model needs six months of account history, which a card applicant does not have",
        {"history_inputs": u["history_inputs"], "total_inputs": u["total_inputs"],
         "dictionary_words": dict_words, "report_words": report_words})
    # B2 and F6: claims
    claims = []
    for cid, words, path, value, better in CLAIMS:
        assert words in report, words
        e = get(R, path)
        v = verdict(value, e["lo"], e["hi"], better)
        claims.append({"id": cid, "words": words, "claimed": value, "validation": e, "verdict": v})
    # rate claims (quintiles, figures by sex) checked two-sided with Wilson intervals on the validation partition;
    # recorded with a verdict, never graded: no finding is made from them
    qrows = [("5.34%", "5.16%"), ("10.07%", "10.60%"), ("14.76%", "13.83%"), ("22.28%", "18.27%"), ("56.11%", "59.27%")]
    for k, (mp, ob) in enumerate(qrows):
        words = f"| {k + 1} | {mp} | {ob} |"
        assert words in report, words
        v = R["calibration"]["quintiles"][k]
        claims.append({"id": f"quintile-{k + 1}", "words": words, "claimed": float(ob[:-1]) / 100,
                       "validation": {"point": v["observed"], "lo": v["lo"], "hi": v["hi"]},
                       "verdict": verdict(float(ob[:-1]) / 100, v["lo"], v["hi"], "none")})
    sexw = {"male": ("66.16%", "12.00%"), "female": ("68.72%", "9.01%")}
    rows = {r["group"]: r for r in R["traits"]["groups"]["sex"]}
    for g, (ap_, dp) in sexw.items():
        r = rows[g]
        for kind, txt, lo, hi, pt in (("approval", ap_, r["approval_lo"], r["approval_hi"], r["approval"]),
                                      ("default_approved", dp, r["default_approved_lo"], r["default_approved_hi"], r["default_approved"])):
            assert txt in report, txt
            claims.append({"id": f"{g}-{kind}", "words": txt, "claimed": float(txt[:-1]) / 100,
                           "validation": {"point": pt, "lo": lo, "hi": hi}, "verdict": verdict(float(txt[:-1]) / 100, lo, hi, "none")})
    words = "independence from ID, target, and demographic columns"
    assert words in report
    claims.append({"id": "excludes_traits", "words": words, "claimed": 0.0,
                   "validation": {"point": R["traits"]["shuffle_max_abs_change"]},
                   "verdict": "holds" if R["traits"]["shuffle_max_abs_change"] == 0 else "does not hold"})
    words = "deterministic refitting"
    assert words in report
    claims.append({"id": "deterministic", "words": words, "claimed": None, "validation": {"point": None},
                   "verdict": "holds" if R["freeze"]["refit_scores_identical"] else "does not hold"})
    R["claims"] = claims
    for c in claims:
        if c["verdict"] == "weaker than claimed":
            rule = "B2" if c["id"] in ("auc", "default_approved") else "F6"
            add("claim-" + c["id"], "blocks approval" if rule == "B2" else "fix before use", rule,
                f"Claim weaker than the validation shows: {c['id']}", {"claimed": c["claimed"], "validation": c["validation"]})
    # F5: reproduction
    rp = R["reproduction"]
    rep_pairs = [("auc", 0.7939, 0.005), ("ap", 0.5835, 0.01), ("log_loss", 0.4078, 0.01), ("brier", 0.1260, 0.01),
                 ("approval", 0.6769, 0.01), ("default_approved", 0.1018, 0.01)]
    off = [(k, c, rp[k]) for k, c, tol in rep_pairs if abs(rp[k] - c) > tol]
    R["reproduction"]["matches"] = {k: bool(abs(rp[k] - c) <= 0.00005) for k, c, _ in rep_pairs}
    if off:
        add("reproduction", "fix before use", "F5", "The report's numbers do not reproduce from its own description", {"off": off})
    # F1: calibration bands
    b = R["calibration"]["bands"]
    mis = [x for x in b if x["miscalibrated"]]
    near = [x for x in b if x["miscalibrated"] and (x["from"], x["to"]) in ((0.15, 0.20), (0.20, 0.25))]
    if near or len(mis) >= 3:
        add("calibration", "fix before use", "F1", "Scores are miscalibrated next to the cutoff",
            {"bands": [(x["from"], x["to"], x["mean_pred"], x["observed"]) for x in mis]})
    else:
        for x in mis:
            add(f"calibration-{x['from']}", "note", "note", "A score band away from the cutoff is miscalibrated", {"band": (x["from"], x["to"])})
    # F2: cutoff at the declared costs
    four = next(e for e in R["decision"]["sweep"] if e["ratio"] == 4)
    if four["both_halves_clear"]:
        add("cutoff", "fix before use", "F2", "At the declared costs the recommended cutoff costs more than a cross-fitted one",
            {"halves": {h: (v["chosen_cutoff"], v["saving"]) for h, v in four["halves"].items()}})
    else:
        add("cutoff", "note", "note", "At the declared costs a cross-fitted cutoff does not save clearly in both halves",
            {"halves": {h: (v["chosen_cutoff"], v["saving"]) for h, v in four["halves"].items()}})
    # F3: stale feed and stresses
    st = R["stale"]["auc_drop"]
    if st["point"] > 0.03 and st["lo"] > 0:
        add("stale", "fix before use", "F3", "Scored on a month-old file, the model loses more than 0.03 AUC", {"auc_drop": st})
    else:
        add("stale", "note", "note", "Scored on a month-old file, the AUC drop stays within 0.03 or its interval includes zero", {"auc_drop": st})
    for x in R["stress"]:
        g = x["gap"]
        if (g["lo"] > 0 or g["hi"] < 0) and abs(g["point"]) > 0.02:
            add("stress-" + x["id"], "fix before use", "F3", f"Calibration breaks in a stress population: {x['label']}", {"gap": g, "psi": x["psi"]})
        elif x["psi"] > 0.25:
            add("stress-" + x["id"], "note", "note", f"The score shifts in a stress population while calibration holds: {x['label']}", {"psi": x["psi"]})
    # F4: protected traits
    for trait, rows in R["traits"]["groups"].items():
        for r in rows:
            if r["ratio"] < 0.8:
                add(f"trait-{trait}-{r['group']}", "fix before use", "F4", f"Approval-rate ratio below 0.80: {trait}, {r['group']}", {"ratio": r["ratio"]})
            if (r["gap_lo"] > 0 or r["gap_hi"] < 0) and abs(r["gap"]) > 0.02:
                add(f"trait-gap-{trait}-{r['group']}", "fix before use", "F4", f"Calibration gap beyond 2 points: {trait}, {r['group']}", {"gap": r["gap"]})
    # F7: challengers
    for name, c in R["challengers"].items():
        d = c["model_minus"]
        if d["hi"] < 0:
            add("challenger-" + name, "fix before use", "F7", f"A challenger beats the model: {name}", {"model_minus": d})
        elif d["point"] < 0.01:
            add("challenger-" + name, "note", "note", f"The model is within 0.01 AUC of a challenger: {name}", {"model_minus": d})
    return F


def predictions(R) -> list[dict]:
    a = R["discrimination"]["auc"]
    band = next(x for x in R["calibration"]["bands"] if x["from"] == 0.20)
    young = R["traits"]["groups"]["age"]
    low = min(young, key=lambda r: r["approval"])
    four = next(e for e in R["decision"]["sweep"] if e["ratio"] == 4)
    return [
        {"n": 1, "held": bool(0.7757 <= a["point"] <= 0.8138)},
        {"n": 2, "held": bool(band["miscalibrated"] and band["observed"] < band["mean_pred"])},
        {"n": 3, "held": bool(R["stale"]["auc_drop"]["point"] > 0.03)},
        {"n": 4, "held": bool(low["group"] == "30 or under" and low["ratio"] < 0.8)},
        {"n": 5, "held": bool(abs(R["challengers"]["logistic"]["model_minus"]["point"]) <= 0.01)},
        {"n": 6, "held": bool(all(v["chosen_cutoff"] > 0.20 for v in four["halves"].values())
                              and any(v["saving"]["lo"] > 0 for v in four["halves"].values()))},
    ]


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
