"""A mailing cut-off on the propensity score, tied to the cost of a send (a follow-up declared after the results, before
this file was written). For each e-mail: spend per buyer, the score at which score x spend per buyer x margin equals
the cost of a send, the share of customers at or above it, and what the send actually added in margin per customer
above it, with the study's Poisson bootstrap (seed 7, 1,000 resamples), scores and cut-off held fixed. Writes
results/cutoff-r3.json with its three predictions scored.

Usage: python3 -I -B tools/cutoff.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]


def added_margin(spend, t, w):
    """Margin per customer the send added: margin x (weighted mean spend of the mailed minus that of the unsent)."""
    m1 = (w * spend * t).sum() / (w * t).sum()
    m0 = (w * spend * (1 - t)).sum() / (w * (1 - t)).sum()
    return MARGIN * (m1 - m0)


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"]))
    score = S["propensity_logistic"]
    out = {"label": "follow-up added after the results (cost cut-off)", "margin": MARGIN, "costs": COSTS,
           "score": "propensity_logistic, out-of-fold", "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]
        sc = score[pair]
        buyers = (t == 1) & (spend > 0)
        per_buyer = float(spend[buyers].mean())
        rows = {}
        for c in COSTS:
            cut = c / (MARGIN * per_buyer)
            above = sc >= cut
            point = added_margin(spend[above], t[above], np.ones(above.sum()))
            rng = np.random.default_rng(BOOT_SEED)
            boot = []
            for _ in range(RESAMPLES):
                w = rng.poisson(1.0, len(t)).astype(np.float64)
                boot.append(added_margin(spend[above], t[above], w[above]))
            lo, hi = float(np.percentile(boot, 2.5)), float(np.percentile(boot, 97.5))
            rows[str(c)] = {"cut_off_score": cut, "share_at_or_above": float(above.mean()),
                            "customers_at_or_above": int(above.sum()), "added_margin_per_customer": float(point),
                            "added_margin_ci": [lo, hi]}
        out["emails"][e] = {"spend_per_buyer": per_buyer, "buyers": int(buyers.sum()), "n": int(len(t)), "by_cost": rows}
        print(e, "spend per buyer", round(per_buyer, 2), {c: (round(r["cut_off_score"], 5), round(r["share_at_or_above"], 3),
              round(r["added_margin_per_customer"], 3), [round(x, 3) for x in r["added_margin_ci"]]) for c, r in rows.items()})
    E = out["emails"]
    scored = {
        "prediction_1": all(0.20 <= E[e]["by_cost"]["0.25"]["share_at_or_above"] <= 0.70 for e in E),
        "prediction_2": E["womens"]["by_cost"]["0.25"]["added_margin_per_customer"] < 0.25,
        "prediction_3": E["mens"]["by_cost"]["0.25"]["added_margin_ci"][0] <= 0.25 <= E["mens"]["by_cost"]["0.25"]["added_margin_ci"][1],
    }
    out["predictions"] = {k: "held" if v else "missed" for k, v in scored.items()}
    (ROOT / "results" / "cutoff-r3.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    print(out["predictions"])


if __name__ == "__main__":
    main()
