"""Score the out-of-fold rankings (protocol-r1.json "evaluation") and write results/<dataset>-r1.json.

Usage: python3 -I -B tools/evaluate.py <hillstrom|criteo> <cache dir> <scores dir> [--seed S] [--points-only]
--points-only skips the bootstrap (used for the Hillstrom refits with other fold seeds).
"""
import json
import math
import sys
from pathlib import Path

import numpy as np
from sklearn.metrics import roc_auc_score

sys.path.insert(0, str(Path(__file__).resolve().parent))
import data  # noqa: E402

ROOT = Path(__file__).resolve().parent.parent
PROTO = json.loads((ROOT / "protocol-r1.json").read_text(encoding="utf-8"))
EV = PROTO["evaluation"]
CUTS = list(range(0, 101))  # percent of the list sent, 1% grid
Z = 1.959963984540054


def load_scores(dataset, scores_dir, seed, n):
    out = {}
    for k in range(PROTO["folds"]["k"]):
        f = np.load(Path(scores_dir) / f"scores-{dataset}-s{seed}-f{k}.npz")
        rows = f["rows"]
        for name in f.files:
            if name == "rows":
                continue
            if name not in out:
                out[name] = np.full(n, np.nan)
            out[name][rows] = f[name].astype(np.float64)
    for name, v in out.items():
        assert not np.isnan(v).any(), f"{name}: a row has no out-of-fold score"
    return out


def wilson(x, n):
    if n == 0:
        return (float("nan"),) * 3
    p = x / n
    d = 1 + Z * Z / n
    c = (p + Z * Z / (2 * n)) / d
    h = Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n)) / d
    return p, c - h, c + h


def newcombe(x1, n1, x2, n2):
    """95% hybrid score interval for p1 - p2 (Newcombe 1998, method 10)."""
    p1, l1, u1 = wilson(x1, n1)
    p2, l2, u2 = wilson(x2, n2)
    d = p1 - p2
    return d, d - math.sqrt((p1 - l1) ** 2 + (u2 - p2) ** 2), d + math.sqrt((u1 - p1) ** 2 + (p2 - l2) ** 2)


def cut_index(N, pct):
    return int(round(N * pct / 100))


def ordered(order, t, outcomes):
    # float32 holds the 0/1 outcomes exactly and halves the memory on the large test; spend stays float64
    ft = np.float32 if len(order) > 1_000_000 else np.float64
    return t[order].astype(ft), {k: v[order].astype(np.float64 if k == "spend" else ft) for k, v in outcomes.items()}


class Curves:
    """Cumulative sums along one ranking's order, read at the cuts."""

    def __init__(self, order, t, outcomes, w=None, pre=None):
        """pre: the same arrays already put in the ranking's order (t first), to skip re-indexing in the bootstrap."""
        if pre is None:
            pre = ordered(order, t, outcomes)
        ot, oys = pre
        ww = np.ones(len(order)) if w is None else w[order]
        self.N = len(order)
        self.idx = np.array([cut_index(self.N, p) for p in CUTS])
        wt = ww * ot
        wc = ww - wt
        self.nt = self._at(wt)
        self.nc = self._at(wc)
        self.s = {}
        for name, oy in oys.items():
            self.s[name] = (self._at(wt * oy), self._at(wc * oy))
        self.W = ww.sum()

    def _at(self, v):
        c = np.concatenate([[0.0], np.cumsum(v)])
        return c[self.idx]

    def gain(self, name):
        """Extra outcome per 1,000 customers on the list when sending to the top k%."""
        st, sc = self.s[name]
        with np.errstate(invalid="ignore", divide="ignore"):
            rt = np.where(self.nt > 0, st / np.maximum(self.nt, 1e-12), 0.0)
            rc = np.where(self.nc > 0, sc / np.maximum(self.nc, 1e-12), 0.0)
        share = (self.nt + self.nc) / self.W
        return (rt - rc) * share * 1000

    def group(self, name, lo, hi):
        """Rates sent and not sent between cuts lo% and hi%."""
        st, sc = self.s[name]
        a, b = CUTS.index(lo), CUTS.index(hi)
        nt, nc = self.nt[b] - self.nt[a], self.nc[b] - self.nc[a]
        yt, yc = st[b] - st[a], sc[b] - sc[a]
        return yt, nt, yc, nc


def qini_coef(g):
    k = np.array(CUTS) / 100
    return float(np.mean(g[1:] - k[1:] * g[-1]))


def main():
    dataset, cache, scores_dir = sys.argv[1], sys.argv[2], sys.argv[3]
    args = sys.argv[4:]
    seed = int(args[args.index("--seed") + 1]) if "--seed" in args else PROTO["folds"]["seed"]
    points_only = "--points-only" in args
    D = data.hillstrom(cache) if dataset == "hillstrom" else data.criteo(cache)
    n_all = len(D["arm"])
    S = load_scores(dataset, scores_dir, seed, n_all)
    tie = np.random.default_rng(7).random(n_all)
    arms = {"hillstrom": {"mens": 1, "womens": 2}, "criteo": {"treated": 1}}[dataset]
    outcomes_all = {"conversion": D["conversion"], "visit": D["visit"]}
    if dataset == "hillstrom":
        outcomes_all["spend"] = D["spend"]
    res = {"dataset": dataset, "seed": seed, "n_rows": n_all, "pairs": {}}

    # ---- the propensity model on the no-send arm: ranking buyers and calibration ----
    c = D["arm"] == 0
    yc = D["conversion"][c]
    rank_scores = {"propensity_logistic": S["propensity_logistic"][c], "propensity_gbm": S["propensity_gbm"][c]}
    if dataset == "hillstrom":
        rank_scores["past_spend"] = D["history"][c] - D["recency"][c] * 1e-6
    prop = {"n": int(c.sum()), "buyers": int(yc.sum()), "auc": {}, "brier": {}, "reliability": {}}
    for name, sc in rank_scores.items():
        prop["auc"][name] = float(roc_auc_score(yc, sc))
    base = S["base_rate_train"][c]
    b0 = float(np.mean((base - yc) ** 2))
    for name in ("propensity_logistic", "propensity_gbm"):
        p = S[name][c]
        b = float(np.mean((p - yc) ** 2))
        prop["brier"][name] = {"brier": b, "brier_base_rate": b0, "skill": 1 - b / b0}
        order = np.lexsort((tie[c], p))
        bins = []
        for i in range(10):
            sl = order[i * len(order) // 10:(i + 1) * len(order) // 10]
            bins.append({"n": int(len(sl)), "mean_predicted": float(p[sl].mean()), "observed": float(yc[sl].mean()),
                         "buyers": int(yc[sl].sum())})
        prop["reliability"][name] = bins
    res["propensity_no_send"] = prop

    boot_n = EV["bootstrap"]["resamples"][dataset]
    for arm_name, a in arms.items():
        pair = np.flatnonzero((D["arm"] == 0) | (D["arm"] == a))
        t = (D["arm"][pair] == a).astype(np.int8)
        outs = {k: v[pair] for k, v in outcomes_all.items()}
        N = len(pair)
        tk = tie[pair]
        orders = {}
        for name in ("propensity_logistic", "propensity_gbm"):
            orders[name] = np.lexsort((tk, -S[name][pair]))
        for base_name in ("response_logistic", "response_gbm", "uplift2_logistic", "uplift2_gbm", "uplift_to_gbm"):
            orders[base_name] = np.lexsort((tk, -S[f"{base_name}_{arm_name}"][pair]))
        if dataset == "hillstrom":
            orders["past_spend"] = np.lexsort((tk, D["recency"][pair], -D["history"][pair]))
        assert sorted(orders) == sorted(r for r in PROTO["models"]["rankings"] if dataset == "hillstrom" or r != "past_spend")
        P = {"n": N, "n_sent": int(t.sum()), "n_not_sent": int(N - t.sum()), "rankings": {}}
        for oc, y in outs.items():
            if oc == "spend":
                continue
            yt, nt, ycn, nc = float((y * t).sum()), float(t.sum()), float((y * (1 - t)).sum()), float((1 - t).sum())
            d, lo, hi = newcombe(yt, nt, ycn, nc)
            P[f"overall_{oc}"] = {"rate_sent": yt / nt, "rate_not_sent": ycn / nc, "effect": d, "lo": lo, "hi": hi,
                                  "sent_buyers": int(yt), "not_sent_buyers": int(ycn)}
        if "spend" in outs:
            s = outs["spend"]
            P["overall_spend"] = {"per_sent": float((s * t).sum() / t.sum()), "per_not_sent": float((s * (1 - t)).sum() / (1 - t).sum())}
        curves = {}
        for name, order in orders.items():
            cv = Curves(order, t, outs)
            curves[name] = cv
            R = {"gain": {oc: [float(x) for x in cv.gain(oc)] for oc in outs}}
            R["qini_coefficient"] = {oc: qini_coef(cv.gain(oc)) for oc in outs}
            dec = []
            for i in range(10):
                row = {"decile": i + 1}
                for oc in ("conversion", "visit"):
                    yt, nt, ycn, nc = cv.group(oc, i * 10, (i + 1) * 10)
                    d, lo, hi = newcombe(yt, nt, ycn, nc)
                    row[oc] = {"sent": int(yt), "n_sent": int(nt), "not_sent": int(ycn), "n_not_sent": int(nc),
                               "rate_sent": yt / nt, "rate_not_sent": ycn / nc, "effect": d, "lo": lo, "hi": hi}
                if "spend" in outs:
                    st, nt, sc_, nc = cv.group("spend", i * 10, (i + 1) * 10)
                    row["spend"] = {"per_sent": st / nt, "per_not_sent": sc_ / nc, "extra_per_sent": st / nt - sc_ / nc}
                dec.append(row)
            R["deciles"] = dec
            for lo_, hi_ in ((0, 30), (30, 100)):
                yt, nt, ycn, nc = cv.group("conversion", lo_, hi_)
                d, lo, hi = newcombe(yt, nt, ycn, nc)
                R[f"conversion_{lo_}_{hi_}"] = {"rate_sent": yt / nt, "rate_not_sent": ycn / nc, "effect": d, "lo": lo,
                                                "hi": hi, "anyway_share": (ycn / nc) / (yt / nt),
                                                "sent_buyers": int(yt), "not_sent_buyers": int(ycn), "n_sent": int(nt),
                                                "n_not_sent": int(nc)}
            P["rankings"][name] = R

        if not points_only:
            rng = np.random.default_rng(EV["bootstrap"]["seed"])
            ks = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
            boot = {name: {oc: [] for oc in outs} for name in orders}
            grp = {name: [] for name in ("propensity_logistic", "uplift2_logistic", "response_logistic")}
            auc_b = {name: [] for name in rank_scores}
            cpos = np.flatnonzero(t == 0)
            pres = {name: ordered(order, t, outs) for name, order in orders.items()}
            for b in range(boot_n):
                w = rng.poisson(1.0, N).astype(np.float64)
                for name, order in orders.items():
                    cv = Curves(order, t, outs, w, pres[name])
                    for oc in outs:
                        g = cv.gain(oc)
                        boot[name][oc].append([float(g[CUTS.index(k)]) for k in ks] + [qini_coef(g)])
                    if name in grp:
                        r = []
                        for lo_, hi_ in ((0, 30), (30, 100)):
                            yt, nt, ycn, nc = cv.group("conversion", lo_, hi_)
                            r += [ycn / nc / (yt / nt), yt / nt - ycn / nc]
                        grp[name].append(r)
                if arm_name in ("mens", "treated"):
                    # AUC on the no-send arm, with the same weights for the no-send customers of the pair
                    wc = w[cpos]
                    ycp = outs["conversion"][cpos]
                    for name in rank_scores:
                        full = S[name] if name != "past_spend" else D["history"] - D["recency"] * 1e-6
                        auc_b[name].append(float(roc_auc_score(ycp, full[pair][cpos], sample_weight=wc)))

            def ci(v):
                v = np.asarray(v)
                return [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))]

            B = {"resamples": boot_n, "k": ks, "gain_ci": {}, "qini_ci": {}, "diff_primary": {}}
            for name in orders:
                B["gain_ci"][name] = {}
                B["qini_ci"][name] = {}
                for oc in outs:
                    arr = np.array(boot[name][oc])
                    B["gain_ci"][name][oc] = [ci(arr[:, j]) for j in range(len(ks))]
                    B["qini_ci"][name][oc] = ci(arr[:, -1])
            a_, b_ = PROTO["models"]["primary_pair"]
            for oc in outs:
                A, Bv = np.array(boot[a_][oc]), np.array(boot[b_][oc])
                d30 = Bv[:, ks.index(30)] - A[:, ks.index(30)]
                dq = Bv[:, -1] - A[:, -1]
                B["diff_primary"][oc] = {"gain30": ci(d30), "qini": ci(dq), "share_uplift_better_gain30": float((d30 > 0).mean())}
            # every other ranking against the propensity model at 30%, conversion
            B["diff_vs_propensity_gain30"] = {}
            A = np.array(boot["propensity_logistic"]["conversion"])
            for name in orders:
                if name == "propensity_logistic":
                    continue
                Bv = np.array(boot[name]["conversion"])
                B["diff_vs_propensity_gain30"][name] = ci(Bv[:, ks.index(30)] - A[:, ks.index(30)])
            B["groups"] = {}
            for name, rows in grp.items():
                arr = np.array(rows)
                B["groups"][name] = {"anyway_share_0_30": ci(arr[:, 0]), "effect_0_30": ci(arr[:, 1]),
                                     "anyway_share_30_100": ci(arr[:, 2]), "effect_30_100": ci(arr[:, 3]),
                                     "anyway_share_top_minus_rest": ci(arr[:, 0] - arr[:, 2]),
                                     "effect_top_minus_rest": ci(arr[:, 1] - arr[:, 3])}
            if auc_b["propensity_logistic"]:
                B["auc_ci"] = {name: ci(v) for name, v in auc_b.items()}
                B["auc_diff_ci"] = {name: ci(np.array(auc_b["propensity_logistic"]) - np.array(v))
                                    for name, v in auc_b.items() if name != "propensity_logistic"}
            P["bootstrap"] = B
        res["pairs"][arm_name] = P
        print(f"{arm_name}: done")
    name = f"{dataset}-r1.json" if seed == PROTO["folds"]["seed"] else f"{dataset}-refit-s{seed}-r1.json"
    out = ROOT / "results" / name
    out.parent.mkdir(exist_ok=True)
    out.write_text(json.dumps(res, indent=1) + "\n", encoding="utf-8")
    print(f"wrote {out.relative_to(ROOT)}")


if __name__ == "__main__":
    main()
