"""The further declared analysis (declared in a file committed before this one was written): holdout size for the top-30% check, the sending
policy with intervals, and the past-spend rule against the propensity list. Hillstrom only, same out-of-fold scores
and the same Poisson bootstrap (seed 7) as the first analysis, model scores held fixed. Writes results/change2-r2.json with the
scores of its four predictions, numbered 1 to 4 in the order declared.

Usage: python3 -I -B tools/change2.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 after_results as ar  # noqa: E402
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"]
KS = [1, 2, 4, 8, 16]
SIZE_RESAMPLES = 200
POLICY_RESAMPLES = 1000
MARGIN = 0.40
COSTS = [0.01, 0.10, 0.25, 0.50]
SHARES = list(range(0, 101, 10))
NAMES = ["propensity_logistic", "uplift2_logistic", "past_spend"]
P_, U_, R_ = NAMES


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


def net(gain_spend, k, c):
    """Net margin per 1,000 customers on the list when sending to the top k%."""
    return MARGIN * gain_spend[k] - c * 1000 * k / 100


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": "added after the results (further declared analysis)", "declared": "in a change file committed before this code", "margin": MARGIN,
           "costs": COSTS, "holdout_size": {}, "policy": {}, "rule_minus_model_share_ci": {}}
    for e, a in (("mens", 1), ("womens", 2)):
        pair = np.flatnonzero((D["arm"] == 0) | (D["arm"] == a))
        t = (D["arm"][pair] == a).astype(np.int8)
        outs = {"conversion": D["conversion"][pair], "spend": D["spend"][pair]}
        orders = ar.orders_for(D, S, pair, e, tie, True)
        pres = {n: ev.ordered(orders[n], t, outs) for n in NAMES}
        n_arm = int(min(t.sum(), len(t) - t.sum()))

        # 1. holdout size: Poisson(k) weights, the spread at k times this test's size
        hs = {"customers_per_arm_now": n_arm, "k": KS, "share_half_width": [], "gap_half_width_per_1000": []}
        for k in KS:
            rng = np.random.default_rng(BOOT_SEED)
            sh, gap = [], []
            for _ in range(SIZE_RESAMPLES):
                w = rng.poisson(k, len(t)).astype(np.float64)
                gp = ev.Curves(orders[P_], t, outs, w, pres[P_]).gain("conversion")
                gu = ev.Curves(orders[U_], t, outs, w, pres[U_]).gain("conversion")
                sh.append(gp[30] / gp[100])
                gap.append(gu[30] - gp[30])
            lo, hi = ci(sh)
            glo, ghi = ci(gap)
            hs["share_half_width"].append((hi - lo) / 2)
            hs["gap_half_width_per_1000"].append((ghi - glo) / 2)
        hw = np.array(hs["share_half_width"])
        kk = np.array(KS, dtype=float)
        a_fit = float((hw * kk ** -0.5).sum() / (kk ** -1.0).sum())
        hs["fit_half_width_at_k1"] = a_fit
        hs["ratio_k16_to_k1"] = float(hw[-1] / hw[0])
        hs["customers_per_arm_for_10_points"] = int(round(n_arm * (a_fit / 0.10) ** 2, -3))
        reach = [k for k, h in zip(KS, hw) if h <= 0.10]
        hs["smallest_measured_k_at_10_points"] = reach[0] if reach else None
        out["holdout_size"][e] = hs
        print(f"{e}: holdout size done")

        # 2 and 3. policy nets and the rule-minus-model share, one set of Poisson(1) resamples
        point = {n: ev.Curves(orders[n], t, outs, None, pres[n]) for n in NAMES}
        pg = {n: point[n].gain("spend") for n in NAMES}
        pc = {n: point[n].gain("conversion") for n in NAMES}
        rng = np.random.default_rng(BOOT_SEED)
        boot_g = {n: [] for n in NAMES}
        boot_share = {n: [] for n in (P_, R_)}
        for _ in range(POLICY_RESAMPLES):
            w = rng.poisson(1.0, len(t)).astype(np.float64)
            for n in NAMES:
                cv = ev.Curves(orders[n], t, outs, w, pres[n])
                boot_g[n].append(cv.gain("spend")[SHARES])
                if n in boot_share:
                    g = cv.gain("conversion")
                    boot_share[n].append(g[30] / g[100])
        pol = {}
        for n in NAMES:
            bg = np.array(boot_g[n])  # resamples x shares
            rows = {}
            for c in COSTS:
                cells = []
                for j, k in enumerate(SHARES):
                    b_net = MARGIN * bg[:, j] - c * 1000 * k / 100
                    b_all = MARGIN * bg[:, -1] - c * 1000
                    cells.append({"share": k, "net": float(net(pg[n], k, c)), "net_ci": ci(b_net),
                                  "minus_everyone_ci": ci(b_net - b_all)})
                best = max(cells, key=lambda x: x["net"])
                rows[str(c)] = {"cells": cells, "best_share": best["share"], "best_net": best["net"]}
            pol[n] = rows
        out["policy"][e] = pol
        d = np.array(boot_share[R_]) - np.array(boot_share[P_])
        out["rule_minus_model_share_ci"][e] = {"point": float(pc[R_][30] / pc[R_][100] - pc[P_][30] / pc[P_][100]),
                                               "ci": ci(d)}
        print(f"{e}: policy done")

    H = out["holdout_size"]
    everyone = {e: out["policy"][e][P_]["0.25"]["cells"][-1]["net_ci"] for e in ("mens", "womens")}
    scored = {
        "prediction_1": all(0.20 <= H[e]["ratio_k16_to_k1"] <= 0.30 for e in H),
        "prediction_2": H["womens"]["customers_per_arm_for_10_points"] >= 150000 and H["mens"]["customers_per_arm_for_10_points"] <= 60000,
        "prediction_3": all(v["ci"][0] <= 0 <= v["ci"][1] for v in out["rule_minus_model_share_ci"].values()),
        "prediction_4": everyone["womens"][1] < 0 and everyone["mens"][0] <= 0 <= everyone["mens"][1],
    }
    out["predictions"] = {k: "held" if v else "missed" for k, v in scored.items()}
    out["everyone_at_0.25_net_ci"] = everyone
    dst = ROOT / "results" / "change2-r2.json"
    dst.write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    for k, v in out["predictions"].items():
        print(k, v)
    for e in H:
        print(e, "half-widths", [round(x, 3) for x in H[e]["share_half_width"]], "per arm for 10 points",
              H[e]["customers_per_arm_for_10_points"], "now", H[e]["customers_per_arm_now"])
    print("rule minus model", {e: [round(x, 3) for x in v["ci"]] for e, v in out["rule_minus_model_share_ci"].items()})
    print("everyone at 0.25", {e: [round(x, 1) for x in v] for e, v in everyone.items()})


if __name__ == "__main__":
    main()
