"""The cost cut-off as a mailing policy (a follow-up declared in CUTOFF-r4.md, committed before this file was written).

For each e-mail and send cost, four policies on the study's out-of-fold scores: the propensity cut-off (mail when
chance of buying x spend per buyer x margin covers the send), the added-margin cut-off (the same with the uplift
model's added chance of buying), the plain ranking (last year's spend, mailing as many as the propensity cut-off) and
everyone. Net margin per 1,000 customers on the list, with the study's Poisson bootstrap (seed 7, 1,000 resamples),
scores and cut-offs held fixed. Writes results/cutoff-r4.json with its three predictions scored.

Usage: python3 -I -B tools/cutoff_policy.py <cache dir> <scores dir>
"""
import json
import sys
from pathlib import Path

import numpy as np

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

ROOT = Path(__file__).resolve().parent.parent
SEED = ev.PROTO["folds"]["seed"]
BOOT_SEED = ev.PROTO["evaluation"]["bootstrap"]["seed"]
RESAMPLES = 1000
MARGIN = ev.PROTO["money_hillstrom"]["margin_on_spend"]["base"]
COSTS = [0.10, 0.25, 0.50]
POLICIES = ["propensity_cut_off", "added_margin_cut_off", "plain_ranking", "everyone"]
DIFFS = [("propensity_cut_off", "everyone"), ("propensity_cut_off", "plain_ranking"),
         ("added_margin_cut_off", "everyone"), ("added_margin_cut_off", "propensity_cut_off")]


def net_per_1000(mask, spend, t, w, c):
    """1,000 x share mailed x (margin x (mean spend mailed minus unsent, within the mailed set) minus cost).
    Arrays are 2-D (resamples x customers) for w, 1-D otherwise."""
    wm = w * mask
    n1 = (wm * t).sum(-1)
    n0 = (wm * (1 - t)).sum(-1)
    m1 = (wm * t * spend).sum(-1) / n1
    m0 = (wm * (1 - t) * spend).sum(-1) / n0
    share = wm.sum(-1) / w.sum(-1)
    return 1000 * share * (MARGIN * (m1 - m0) - c)


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


def main():
    cache, scores_dir = sys.argv[1], sys.argv[2]
    D = data.hillstrom(cache)
    S = ev.load_scores("hillstrom", scores_dir, SEED, len(D["arm"]))
    tie = np.random.default_rng(7).random(len(D["arm"]))
    out = {"label": "follow-up computed after the results (cost cut-off as a mailing policy)",
           "declared": "CUTOFF-r4.md, committed before this code", "margin": MARGIN, "costs": COSTS,
           "scores": "out-of-fold, random five-part split (the data carries no dates)", "emails": {}}
    for e, a in (("mens", 1), ("womens", 2)):
        pair = np.flatnonzero((D["arm"] == 0) | (D["arm"] == a))
        t = (D["arm"][pair] == a).astype(np.float64)
        spend = D["spend"][pair].astype(np.float64)
        prop = S["propensity_logistic"][pair]
        upl = S[f"uplift2_logistic_{e}"][pair]
        per_buyer = float(spend[(t == 1) & (spend > 0)].mean())
        spend_order = np.lexsort((tie[pair], D["recency"][pair], -D["history"][pair]))
        n = len(t)
        rng = np.random.default_rng(BOOT_SEED)
        W = rng.poisson(1.0, (RESAMPLES, n)).astype(np.float32)  # one set of resamples for every policy and cost
        rows = {}
        for c in COSTS:
            masks = {"propensity_cut_off": (prop * per_buyer * MARGIN >= c).astype(np.float64),
                     "added_margin_cut_off": (upl * per_buyer * MARGIN >= c).astype(np.float64),
                     "everyone": np.ones(n)}
            k = int(masks["propensity_cut_off"].sum())
            plain = np.zeros(n)
            plain[spend_order[:k]] = 1.0
            masks["plain_ranking"] = plain
            pol, boot = {}, {}
            for p in POLICIES:
                m = masks[p]
                boot[p] = np.concatenate([net_per_1000(m, spend, t, W[i:i + 100].astype(np.float64), c)
                                          for i in range(0, RESAMPLES, 100)])  # in chunks, to bound memory
                pol[p] = {"share_mailed": float(m.mean()), "customers_mailed": int(m.sum()),
                          "mailed_per_100000": int(round(m.mean() * 100000, -2)),
                          "net_per_1000": float(net_per_1000(m, spend, t, np.ones(n), c)), "net_ci": ci(boot[p])}
            diffs = {f"{x}_minus_{y}": {"net_per_1000": pol[x]["net_per_1000"] - pol[y]["net_per_1000"],
                                        "ci": ci(boot[x] - boot[y])} for x, y in DIFFS}
            rows[str(c)] = {"policies": pol, "differences": diffs}
        out["emails"][e] = {"spend_per_buyer": per_buyer, "n": int(n), "by_cost": rows}
        r = rows["0.25"]
        print(e, {p: (round(v["share_mailed"], 3), round(v["net_per_1000"], 1), [round(x, 1) for x in v["net_ci"]])
                  for p, v in r["policies"].items()})
        print(e, {d: (round(v["net_per_1000"], 1), [round(x, 1) for x in v["ci"]]) for d, v in r["differences"].items()})
    E = {e: out["emails"][e]["by_cost"]["0.25"]["differences"] for e in ("mens", "womens")}
    wd = E["womens"]["propensity_cut_off_minus_everyone"]
    md = E["mens"]["propensity_cut_off_minus_everyone"]
    scored = {
        "prediction_1": wd["net_per_1000"] > 0 and wd["ci"][0] <= 0 <= wd["ci"][1],
        "prediction_2": md["ci"][0] <= 0 <= md["ci"][1],
        "prediction_3": E["womens"]["added_margin_cut_off_minus_propensity_cut_off"]["net_per_1000"] > 0,
    }
    out["predictions"] = {k: "held" if v else "missed" for k, v in scored.items()}
    (ROOT / "results" / "cutoff-r4.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    print(out["predictions"])


if __name__ == "__main__":
    main()
