"""Generate figures for the 'Fairness is a choice, not a metric' note.

Synthetic credit applicants in two groups (A: thin credit file and a higher
default rate, B: thick file) -> XGBoost PD models on different feature sets ->
four fairness verdicts on one model, the selective-labels gap, proxy
reconstruction, the impossibility arithmetic, a cloud of equally strong models,
a crafted feature set and a monitoring series -> SVG figures in light and dark
variants, plus results.json with the numbers quoted in prose.
"""
import json
import os
import sys

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.ticker
import xgboost as xgb
from matplotlib.patches import Patch, Rectangle
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

SEED = 42
rng = np.random.default_rng(SEED)
OUT = sys.argv[1] if len(sys.argv) > 1 else "figs"
os.makedirs(OUT, exist_ok=True)

TEAL = "#009485"    # group A / calibrated
INDIGO = "#526cfe"  # group B / second series
CORAL = "#e6695b"   # warning / highlight

MODES = {
    "light": dict(text="#212121", muted="#757575", grid="#e3e3e3", faint="#bdbdbd",
                  surface="#ffffff"),
    "dark": dict(text="#dee2ef", muted="#8a91a8", grid="#3a3e4d", faint="#565b6e",
                 surface="#1e2129"),
}

WEB_FONTS = "Roboto, 'DejaVu Sans', sans-serif"

CUTOFF = 0.10          # approve when the predicted PD is below 10%
N_TRAIN, N_TEST = 100_000, 200_000
SHARE_A = 0.30

# feature: (family, loading on individual risk in A, in B, shift for group A, shift for sex)
# Bureau features say a lot about a thick file (B) and little about a thin one (A).
# Shopping features say a moderate amount about everyone. Sex has no effect on
# default; it only moves the features, mostly what people buy.
SPEC = {
    "file_length":       ("bureau", -0.10, -0.30, -2.20, 0.10),
    "delinquencies":     ("bureau", 0.15, 0.70, 0.20, 0.15),
    "utilization":       ("bureau", 0.15, 0.60, 0.30, -0.20),
    "inquiries":         ("bureau", 0.15, 0.50, 0.60, 0.20),
    "active_loans":      ("bureau", 0.10, 0.50, -0.50, 0.25),
    "months_since_dpd":  ("bureau", -0.10, -0.55, 0.00, -0.15),
    "installment_share": ("bureau", 0.10, 0.40, 0.40, -0.20),
    "tenure":            ("shopping", -0.50, -0.30, -1.60, -0.10),
    "basket_value":      ("shopping", -0.50, -0.25, -0.30, 0.15),
    "purchase_freq":     ("shopping", -0.55, -0.25, 0.20, -0.15),
    "return_rate":       ("shopping", 0.50, 0.20, 0.10, -0.20),
    "cash_on_delivery":  ("shopping", 0.60, 0.30, 0.30, 0.15),
    "night_share":       ("shopping", 0.40, 0.20, 1.00, 0.20),
    "electronics_share": ("shopping", 0.10, 0.05, 0.30, 0.70),
    "home_share":        ("shopping", -0.20, -0.10, -0.40, -0.60),
    "fashion_share":     ("shopping", 0.15, 0.10, 0.20, -0.70),
}
FEATURES = list(SPEC)
IDX = {f: i for i, f in enumerate(FEATURES)}
LABELS = {f: f.replace("_", " ") for f in FEATURES}
LABELS.update(months_since_dpd="months since delinquency", cash_on_delivery="cash on delivery",
              night_share="night-time share", electronics_share="electronics share",
              home_share="home & garden share", fashion_share="fashion share",
              installment_share="instalment share", purchase_freq="purchase frequency")


def make_data(n, rng, risk_shift_a=0.0, share_a=SHARE_A):
    """Applicants: group (1 = A), sex, default flag and the 16 candidate features."""
    g = (rng.random(n) < share_a).astype(int)
    sex = (rng.random(n) < 0.5).astype(int)
    r = rng.normal(0, 1, n) + risk_shift_a * g          # individual risk
    z = -3.35 + 1.0 * r + 0.9 * g                        # A defaults more often
    y = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
    X = np.empty((n, len(FEATURES)))
    for j, (_, lam_a, lam_b, shift_g, shift_sex) in enumerate(SPEC.values()):
        lam = np.where(g == 1, lam_a, lam_b)
        X[:, j] = (lam * r + shift_g * g + shift_sex * sex
                   + np.sqrt(1 - lam ** 2) * rng.normal(0, 1, n))
    return X, y, g, sex


X, y, g, sex = make_data(N_TRAIN, rng)
Xt, yt, gt, sext = make_data(N_TEST, rng)
A, B = gt == 1, gt == 0
PARAMS = dict(n_estimators=150, max_depth=3, learning_rate=0.1, subsample=0.9,
              tree_method="hist", random_state=SEED, eval_metric="logloss")


def cols(names):
    return [IDX[f] for f in names]


def fit_pd(names):
    c = cols(names)
    return xgb.XGBClassifier(**PARAMS).fit(X[:, c], y).predict_proba(Xt[:, c])[:, 1]


def gini(y_, p_):
    return 2 * roc_auc_score(y_, p_) - 1


def evaluate(p):
    """Power, calibration and error rates of one PD vector, overall and by group."""
    rej = p >= CUTOFF
    out = {"gini": gini(yt, p), "approval": float(1 - rej.mean())}
    for name, m in (("A", A), ("B", B)):
        good, bad = m & (yt == 0), m & (yt == 1)
        out[name] = {
            "gini": gini(yt[m], p[m]),
            "default_rate": float(yt[m].mean()),
            "mean_pd": float(p[m].mean()),
            "approval": float(1 - rej[m].mean()),
            "good_rejected": float(rej[good].mean()),    # false positive rate
            "bad_rejected": float(rej[bad].mean()),      # true positive rate
            "bad_approved": float(1 - rej[bad].mean()),
            "bad_among_rejected": float(yt[m & rej].mean()),   # PPV
        }
    out["approval_gap"] = out["B"]["approval"] - out["A"]["approval"]
    out["good_rejected_gap"] = out["A"]["good_rejected"] - out["B"]["good_rejected"]
    return out


def recover_auc(names, target_tr, target_te):
    """How well a plain classifier recovers a hidden attribute from the features."""
    c = cols(names)
    clf = LogisticRegression(max_iter=500).fit(X[:, c], target_tr)
    return roc_auc_score(target_te, clf.predict_proba(Xt[:, c])[:, 1])


def rounded(d, k=4):
    if isinstance(d, dict):
        return {a: rounded(b, k) for a, b in d.items()}
    if isinstance(d, (list, tuple)):
        return [rounded(b, k) for b in d]
    return round(float(d), k) if isinstance(d, (float, np.floating)) else d


def style(mode):
    c = MODES[mode]
    plt.rcParams.update({
        "figure.facecolor": "none", "axes.facecolor": "none",
        "savefig.facecolor": "none", "svg.fonttype": "none",
        "font.family": "DejaVu Sans", "font.size": 11,
        "text.color": c["text"], "axes.edgecolor": c["faint"],
        "axes.labelcolor": c["muted"], "xtick.color": c["muted"],
        "ytick.color": c["muted"], "axes.grid": True, "axes.axisbelow": True,
        "grid.color": c["grid"], "grid.linewidth": 0.6,
        "axes.spines.top": False, "axes.spines.right": False,
        "axes.titlesize": 11, "axes.titlecolor": c["text"],
        "legend.labelcolor": c["text"],
    })
    return c


def save(fig, name, mode):
    path = f"{OUT}/{name}-{mode}.svg"
    fig.savefig(path, bbox_inches="tight", pad_inches=0.18)
    plt.close(fig)
    # Browsers without DejaVu Sans would fall back to a serif face inside <img>.
    with open(path, encoding="utf-8") as f:
        svg = f.read()
    with open(path, "w", encoding="utf-8") as f:
        f.write(svg.replace("font-family: 'DejaVu Sans'", f"font-family: {WEB_FONTS}"))


# ---------------------------------------------------------------- the current model
# Set 1: what a power-first selection gives -- the whole bureau report plus two
# shopping features. The group is not an input.
SET1 = [f for f in FEATURES if SPEC[f][0] == "bureau"] + ["tenure", "basket_value"]
pd1 = fit_pd(SET1)
ev1 = evaluate(pd1)
results = {"n_train": N_TRAIN, "n_test": N_TEST, "cutoff": CUTOFF,
           "default_rate": float(yt.mean()), "share_a": float(A.mean()),
           "set1": {"features": SET1, **ev1}}


def reliability(p, y_, n_bins=10):
    edges = np.quantile(p, np.linspace(0, 1, n_bins + 1))
    idx = np.clip(np.searchsorted(edges, p, side="right") - 1, 0, n_bins - 1)
    return (np.array([p[idx == b].mean() for b in range(n_bins)]),
            np.array([y_[idx == b].mean() for b in range(n_bins)]))


def fig_verdicts(mode):
    c = style(mode)
    fig, (a1, a2, a3) = plt.subplots(1, 3, figsize=(8.6, 3.0),
                                     gridspec_kw=dict(width_ratios=[1.25, 1, 1], wspace=0.55))
    lim = 0.42
    a1.plot([0, lim], [0, lim], color=c["faint"], lw=1)
    for m, col, lab in ((A, TEAL, "group A"), (B, INDIGO, "group B")):
        mp, fr = reliability(pd1[m], yt[m])
        a1.plot(mp, fr, "o-", color=col, lw=2, ms=4.5, label=lab)
    a1.set_xlim(0, lim)
    a1.set_ylim(0, lim)
    a1.set_xticks([0, 0.2, 0.4], ["0%", "20%", "40%"])
    a1.set_yticks([0, 0.2, 0.4], ["0%", "20%", "40%"])
    a1.set_xlabel("predicted PD")
    a1.set_ylabel("observed default rate")
    a1.set_title("Calibration", loc="left")
    a1.legend(frameon=False, fontsize=9, loc="upper left")
    for ax, key, title in ((a2, "approval", "Approval rate"), (a3, "good_rejected", "Good clients rejected")):
        vals = [ev1["A"][key], ev1["B"][key]]
        ax.bar(["A", "B"], np.array(vals) * 100, color=[TEAL, INDIGO], width=0.5)
        for i, v in enumerate(vals):
            ax.text(i, v * 100 + 2, f"{v:.0%}", ha="center", fontsize=10, color=c["text"])
        ax.set_ylim(0, 100)
        ax.set_yticks([0, 50, 100], ["0%", "50%", "100%"])
        ax.set_xlabel("group")
        ax.set_title(title, loc="left")
        ax.grid(axis="x", visible=False)
    save(fig, "verdicts", mode)


# ---------------------------------------------------------------- selective labels
# The previous policy: a three-feature bureau scorecard approving 60% of
# applicants. A real lender knows the outcome only for those it approved.
OLD = ["file_length", "delinquencies", "utilization"]
old_clf = LogisticRegression(max_iter=500).fit(X[:, cols(OLD)], y)
old_score = old_clf.predict_proba(Xt[:, cols(OLD)])[:, 1]
old_ok = old_score <= np.quantile(old_score, 0.60)
rej1 = pd1 >= CUTOFF
labels = {}
for name, m in (("A", A), ("B", B)):
    good = m & (yt == 0)
    labels[name] = {
        "approved_by_old_policy": float(old_ok[m].mean()),
        "good_rejected_observable": float(rej1[good & old_ok].mean()),
        "good_rejected_true": float(rej1[good].mean()),
    }
labels["gap_observable"] = (labels["A"]["good_rejected_observable"]
                            - labels["B"]["good_rejected_observable"])
labels["gap_true"] = labels["A"]["good_rejected_true"] - labels["B"]["good_rejected_true"]
labels["share_a_applicants"] = float(A.mean())
labels["share_a_with_outcome"] = float(A[old_ok].mean())
results["selective_labels"] = labels


def fig_labels(mode):
    c = style(mode)
    fig, ax = plt.subplots(figsize=(6.4, 3.4))
    xs = np.arange(2)
    wd = 0.3
    series = [("A", TEAL, "group A"), ("B", INDIGO, "group B")]
    for k, (name, col, lab) in enumerate(series):
        vals = [labels[name]["good_rejected_observable"], labels[name]["good_rejected_true"]]
        ax.bar(xs + (k - 0.5) * (wd + 0.03), np.array(vals) * 100, wd, color=col, label=lab)
        for x_, v in zip(xs, vals):
            ax.text(x_ + (k - 0.5) * (wd + 0.03), v * 100 + 1.2, f"{v:.0%}", ha="center",
                    fontsize=10, color=c["text"])
    ax.set_xticks(xs, ["what the lender can compute\n(approved by the old policy)",
                       "the truth\n(every applicant)"])
    ax.set_ylabel("good clients rejected (%)")
    ax.set_ylim(0, max(labels["A"]["good_rejected_true"] * 100 + 10, 30))
    ax.grid(axis="x", visible=False)
    ax.legend(frameon=False, fontsize=9, loc="upper left")
    save(fig, "labels", mode)


# ---------------------------------------------------------------- proxies
# (a) The group is not in set 1 -- can it be read back from set 1?
group_auc = {f: recover_auc([f], g, gt) for f in SET1}
group_auc_all = recover_auc(SET1, g, gt)
# Remove every feature that gives the group away on its own and refit.
GROUP_PROXIES = [f for f in SET1 if max(group_auc[f], 1 - group_auc[f]) > 0.60]
no_proxy = [f for f in SET1 if f not in GROUP_PROXIES]
ev_np = evaluate(fit_pd(no_proxy))
results["group_proxies"] = {
    "auc_recover_group_set1": group_auc_all,
    "auc_by_feature": {f: max(v, 1 - v) for f, v in group_auc.items()},
    "removed": GROUP_PROXIES,
    "auc_recover_group_without": recover_auc(no_proxy, g, gt),
    "without": ev_np,
}

# (b) Sex is in no model. The first candidate model used all sixteen features.
sex_auc = {f: recover_auc([f], sex, sext) for f in FEATURES}
sex_auc = {f: max(v, 1 - v) for f, v in sex_auc.items()}
sex_auc_all = recover_auc(FEATURES, sex, sext)
results["sex_proxies"] = {"by_feature": sex_auc, "all_features": sex_auc_all,
                          "set1": recover_auc(SET1, sex, sext)}


def fig_proxy(mode):
    c = style(mode)
    fig, ax = plt.subplots(figsize=(6.4, 5.2))
    order = sorted(FEATURES, key=lambda f: sex_auc[f])
    names = [LABELS[f] for f in order] + ["all sixteen together"]
    vals = [sex_auc[f] for f in order] + [sex_auc_all]
    ys = list(range(len(order))) + [len(order) + 0.6]
    ax.barh(ys, np.array(vals) - 0.5, left=0.5, color=[INDIGO] * len(order) + [CORAL],
            height=0.62)
    ax.set_yticks(ys, names)
    for y_, v in zip(ys, vals):
        ax.text(v + 0.006, y_, f"{v:.2f}", va="center", fontsize=9.5, color=c["text"])
    ax.set_xlim(0.5, max(vals) + 0.06)
    ax.set_ylim(-0.7, ys[-1] + 0.7)
    ax.set_xlabel("AUC of recovering sex (0.5 = coin flip)")
    ax.grid(axis="y", visible=False)
    save(fig, "proxy", mode)


# ---------------------------------------------------------------- impossibility
# Arithmetic, not simulation: 100 clients per group, 20 vs 5 defaulters, the same
# share of defaulters rejected (60%), the same share of defaulters among the
# rejected (half).
WAFFLE = {"A": dict(bad=20, bad_rej=12, good_rej=12), "B": dict(bad=5, bad_rej=3, good_rej=3)}
results["impossibility_example"] = {
    k: {**v, "good_rejected_rate": v["good_rej"] / (100 - v["bad"])} for k, v in WAFFLE.items()}
results["identity_set1"] = {}
for name in ("A", "B"):
    e = ev1[name]
    p_, ppv, tpr = e["default_rate"], e["bad_among_rejected"], e["bad_rejected"]
    results["identity_set1"][name] = {
        "p": p_, "ppv": ppv, "tpr": tpr, "fpr": e["good_rejected"],
        "fpr_from_identity": p_ / (1 - p_) * (1 - ppv) / ppv * tpr}


def fig_impossibility(mode):
    c = style(mode)
    fig, axes = plt.subplots(1, 2, figsize=(6.6, 3.5), gridspec_kw=dict(wspace=0.12))
    kinds = [("bad, rejected", CORAL, 1.0), ("bad, approved", CORAL, 0.35),
             ("good, rejected", INDIGO, 1.0), ("good, approved", c["faint"], 0.45)]
    for ax, (name, w) in zip(axes, WAFFLE.items()):
        counts = [w["bad_rej"], w["bad"] - w["bad_rej"], w["good_rej"],
                  100 - w["bad"] - w["good_rej"]]
        cells = [k for k, n in enumerate(counts) for _ in range(n)]
        for i, k in enumerate(cells):
            ax.add_patch(Rectangle((i % 10 + 0.07, 9 - i // 10 + 0.07), 0.86, 0.86,
                                   facecolor=kinds[k][1], alpha=kinds[k][2], linewidth=0))
        ax.set_xlim(0, 10)
        ax.set_ylim(-0.1, 10)
        ax.set_aspect("equal")
        ax.axis("off")
        good = 100 - w["bad"]
        ax.set_title(f"group {name}", loc="left", fontweight="bold")
        ax.text(0, -0.75, f"{w['good_rej']} of {good} good clients rejected"
                          f" = {w['good_rej'] / good:.0%}", fontsize=10, color=c["text"], va="top")
    fig.legend(handles=[Patch(facecolor=col, alpha=al, label=lab) for lab, col, al in kinds],
               frameon=False, fontsize=9, ncol=4, loc="lower center",
               bbox_to_anchor=(0.5, -0.12), handlelength=1, handleheight=1, columnspacing=1.2)
    save(fig, "impossibility", mode)


# ---------------------------------------------------------------- calibration decides
def fig_density(mode):
    c = style(mode)
    fig, ax = plt.subplots(figsize=(6.4, 3.4))
    grid = np.linspace(0, 0.4, 65)
    mid = (grid[:-1] + grid[1:]) / 2
    top = 0
    for name, m, col in (("A", A, TEAL), ("B", B, INDIGO)):
        dens = np.histogram(pd1[m & (yt == 0)], grid, density=True)[0]
        top = max(top, dens.max())
        ax.plot(mid, dens, color=col, lw=2, label=f"group {name}")
        ax.fill_between(mid, 0, dens, where=mid >= CUTOFF, color=col, alpha=0.18, linewidth=0)
    ax.axvline(CUTOFF, color=c["text"], lw=1)
    ax.text(CUTOFF + 0.006, top * 0.92, "cutoff", fontsize=9.5, color=c["text"])
    ax.text(CUTOFF + 0.03, top * 0.42,
            f"good clients rejected:\n{ev1['A']['good_rejected']:.0%} of group A, "
            f"{ev1['B']['good_rejected']:.0%} of group B", fontsize=9.5, color=c["text"])
    ax.set_xlim(0, 0.4)
    ax.set_ylim(0, top * 1.05)
    ax.set_xticks([0, 0.1, 0.2, 0.3, 0.4], ["0%", "10%", "20%", "30%", "40%"])
    ax.set_yticks([])
    ax.set_xlabel("predicted PD of clients who went on to repay")
    ax.set_ylabel("density")
    ax.grid(visible=False)
    ax.legend(frameon=False, fontsize=9, loc="upper right")
    save(fig, "density", mode)


# ---------------------------------------------------------------- Rashomon cloud
# 300 models, each on a random set of 6-10 of the sixteen features. Same
# algorithm, same data, same cutoff.
N_MODELS = 300
CAL_TOL = 0.05         # mean PD within 5% of the observed default rate
BAND = 0.01            # "the same power": within one Gini point of set 1
cloud_rng = np.random.default_rng(SEED + 1)
cloud = []
for _ in range(N_MODELS):
    names = [FEATURES[i] for i in sorted(cloud_rng.choice(
        len(FEATURES), int(cloud_rng.integers(6, 11)), replace=False))]
    p = fit_pd(names)
    cloud.append({"features": names, **evaluate(p)})


def cal_ratio(e, name):
    return e[name]["default_rate"] / e[name]["mean_pd"]


def cal_state(e):
    r = cal_ratio(e, "A")
    return "calibrated" if abs(r - 1) <= CAL_TOL else ("understated" if r > 1 else "overstated")


for e in cloud:
    e["in_band"] = abs(e["gini"] - ev1["gini"]) <= BAND
    e["state"] = cal_state(e)
band = [e for e in cloud if e["in_band"]]
for e in band:
    e["sex_auc"] = recover_auc(e["features"], sex, sext)
results["cloud"] = {
    "n_models": N_MODELS, "n_in_band": len(band),
    "gini_range": [min(e["gini"] for e in cloud), max(e["gini"] for e in cloud)],
    "band_states": {s: sum(e["state"] == s for e in band)
                    for s in ("calibrated", "understated", "overstated")},
    "band_gap_range": [min(e["approval_gap"] for e in band),
                       max(e["approval_gap"] for e in band)],
    "band_gap_range_calibrated": [
        min(e["approval_gap"] for e in band if e["state"] == "calibrated"),
        max(e["approval_gap"] for e in band if e["state"] == "calibrated")],
    "band_good_rejected_a_range_calibrated": [
        min(e["A"]["good_rejected"] for e in band if e["state"] == "calibrated"),
        max(e["A"]["good_rejected"] for e in band if e["state"] == "calibrated")],
    "band_mean_gap_by_state": {
        s: float(np.mean([e["approval_gap"] for e in band if e["state"] == s]))
        for s in ("calibrated", "understated", "overstated")
        if any(e["state"] == s for e in band)},
}

# ---------------------------------------------------------------- crafting
# Set 2: among the equally strong models that stay calibrated in both groups and
# do not give sex away more than set 1 does (plus a small tolerance), the one
# that tells group A's clients apart best.
SEX_TOL = 0.02
sex_auc_set1 = results["sex_proxies"]["set1"]
eligible = [e for e in band if e["state"] == "calibrated"
            and abs(cal_ratio(e, "B") - 1) <= CAL_TOL
            and e["sex_auc"] <= sex_auc_set1 + SEX_TOL]
ev2 = max(eligible, key=lambda e: e["A"]["gini"])
SET2 = ev2["features"]
results["set2"] = {k: v for k, v in ev2.items()}
results["set2"]["n_eligible"] = len(eligible)
results["set2"]["n_bureau"] = sum(SPEC[f][0] == "bureau" for f in SET2)
results["set1"]["n_bureau"] = sum(SPEC[f][0] == "bureau" for f in SET1)
results["set1"]["sex_auc"] = sex_auc_set1
results["set1"]["cal_ratio"] = {n: cal_ratio(ev1, n) for n in ("A", "B")}
results["set2"]["cal_ratio"] = {n: cal_ratio(ev2, n) for n in ("A", "B")}


def fig_rashomon(mode):
    c = style(mode)
    fig, ax = plt.subplots(figsize=(6.6, 4.2))
    lo, hi = ev1["gini"] - BAND, ev1["gini"] + BAND
    ax.axvspan(lo * 100, hi * 100, color=c["muted"], alpha=0.13, linewidth=0)
    rest = [e for e in cloud if not e["in_band"]]
    ax.scatter([e["gini"] * 100 for e in rest], [e["approval_gap"] * 100 for e in rest],
               s=14, color=c["faint"], linewidths=0, label="other feature sets")
    marks = [("calibrated", TEAL, "o", "equally strong, calibrated in group A"),
             ("understated", CORAL, "v", "equally strong, group A's PD understated"),
             ("overstated", INDIGO, "^", "equally strong, group A's PD overstated")]
    for state, col, mk, lab in marks:
        pts = [e for e in band if e["state"] == state]
        if pts:
            ax.scatter([e["gini"] * 100 for e in pts], [e["approval_gap"] * 100 for e in pts],
                       s=46, color=col, marker=mk, edgecolors=c["surface"], linewidths=1.2,
                       label=lab, zorder=3)
    x_lab = max(e["gini"] for e in cloud) * 100 + 0.55
    hi_first = ev1["approval_gap"] >= ev2["approval_gap"]
    for e, lab, up in ((ev1, "set 1", hi_first), (ev2, "set 2", not hi_first)):
        xy = (e["gini"] * 100, e["approval_gap"] * 100)
        ax.scatter(*xy, s=150, facecolors="none", edgecolors=c["text"], linewidths=1.4, zorder=4)
        ax.annotate(lab, xy, xytext=(x_lab, xy[1] + (2.5 if up else -2.5)), fontsize=9.5,
                    color=c["text"], va="center",
                    arrowprops=dict(arrowstyle="-", color=c["text"], lw=0.8,
                                    shrinkA=2, shrinkB=7))
    ax.set_xlim(right=x_lab + 1.1)
    ax.set_xlabel("model power overall (Gini, %)")
    ax.set_ylabel("approval gap, B − A (pp)")
    ax.legend(frameon=False, fontsize=9, loc="lower left", bbox_to_anchor=(-0.01, 1.0))
    save(fig, "rashomon", mode)


def fig_crafting(mode):
    c = style(mode)
    fig, ax = plt.subplots(figsize=(6.4, 3.4))
    xs = np.arange(3)
    wd = 0.3
    v1 = [ev1["gini"], ev1["A"]["gini"], ev1["B"]["gini"]]
    v2 = [ev2["gini"], ev2["A"]["gini"], ev2["B"]["gini"]]
    for k, (vals, col, lab) in enumerate(((v1, c["faint"], "set 1 (current)"),
                                          (v2, CORAL, "set 2 (chosen for group A)"))):
        ax.bar(xs + (k - 0.5) * (wd + 0.03), np.array(vals) * 100, wd, color=col, label=lab)
        for x_, v in zip(xs, vals):
            ax.text(x_ + (k - 0.5) * (wd + 0.03), v * 100 + 1.2, f"{v * 100:.1f}",
                    ha="center", fontsize=9.5, color=c["text"])
    ax.set_xticks(xs, ["all applicants", "group A", "group B"])
    ax.set_ylabel("model power (Gini, %)")
    ax.set_ylim(0, max(v1 + v2) * 100 + 14)
    ax.grid(axis="x", visible=False)
    ax.legend(frameon=False, fontsize=9, loc="upper left")
    save(fig, "crafting", mode)


# ---------------------------------------------------------------- monitoring
# Equal approval is not what set 2 was chosen for, but the gap is watched all
# the same: 24 months of 20,000 applicants. In months 17-18 a campaign brings in
# riskier group-A applicants. Reference level: the first six months.
MONTHS, PER_MONTH, REF, TOL = 24, 20_000, 6, 0.03
CAMPAIGN = (16, 17)    # zero-based months 17 and 18
c2 = cols(SET2)
model2 = xgb.XGBClassifier(**PARAMS).fit(X[:, c2], y)
mon_rng = np.random.default_rng(SEED + 2)
gaps = []
for mth in range(MONTHS):
    Xm, _, gm, _ = make_data(PER_MONTH, mon_rng,
                             risk_shift_a=0.25 if mth in CAMPAIGN else 0.0)
    ok = model2.predict_proba(Xm[:, c2])[:, 1] < CUTOFF
    gaps.append(ok[gm == 0].mean() - ok[gm == 1].mean())
gaps = np.array(gaps)
ref_level = float(gaps[:REF].mean())
alerts = np.abs(gaps - ref_level) > TOL
results["monitoring"] = {
    "reference_gap": ref_level, "tolerance": TOL,
    "alert_months": [int(i) + 1 for i in np.where(alerts)[0]],
    "max_gap": float(gaps.max()),
    "quiet_sd": float(np.delete(gaps, CAMPAIGN).std()),
}


def fig_monitoring(mode):
    c = style(mode)
    fig, ax = plt.subplots(figsize=(6.4, 3.4))
    months = np.arange(1, MONTHS + 1)
    ax.axhspan((ref_level - TOL) * 100, (ref_level + TOL) * 100, color=TEAL, alpha=0.12,
               linewidth=0)
    ax.axhline(ref_level * 100, color=c["faint"], lw=1)
    ax.plot(months, gaps * 100, color=INDIGO, lw=2, marker="o", ms=4.5)
    ax.scatter(months[alerts], gaps[alerts] * 100, s=60, color=CORAL, zorder=3,
               edgecolors=c["surface"], linewidths=1.2)
    ax.text(1, (ref_level + TOL) * 100 + 0.4, "tolerance around the level at approval",
            fontsize=9, color=c["muted"])
    if alerts.any():
        i = int(np.argmax(gaps))
        ax.annotate("alert → review", (months[i], gaps[i] * 100), xytext=(-12, 2),
                    textcoords="offset points", ha="right", fontsize=9.5, color=c["text"])
    ax.set_xlabel("month")
    ax.set_ylabel("approval gap, B − A (pp)")
    ax.set_xticks([1, 6, 12, 18, 24])
    ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(5))
    ax.set_ylim((ref_level - 2.2 * TOL) * 100, gaps.max() * 100 + 2.5)
    save(fig, "monitoring", mode)


for mode in MODES:
    fig_verdicts(mode)
    fig_labels(mode)
    fig_proxy(mode)
    fig_impossibility(mode)
    fig_density(mode)
    fig_rashomon(mode)
    fig_crafting(mode)
    fig_monitoring(mode)

results["cloud_models"] = [
    {"features": e["features"], "gini": e["gini"], "approval_gap": e["approval_gap"],
     "state": e["state"], "in_band": e["in_band"]} for e in cloud]
results = rounded(results)
with open(f"{OUT}/results.json", "w") as f:
    json.dump(results, f, indent=1)
print(json.dumps({k: v for k, v in results.items() if k != "cloud_models"}, indent=1))
