"""The study, in three stages run in this order.

  train     training cohorts only (the Oct 2014 rows are dropped before anything is computed): signal AUCs with
            bootstrap intervals, the day-14 rule, the save-offer arithmetic. Writes results/train-r1.json and
            results/rule-r1.json.
  holdout   reads the committed rule file, applies it unchanged to the Oct 2014 cohort. Writes results/holdout-r1.json.
  describe  all four cohorts: the funnel, cancellations by 30-day period, the reconciliation of the two tables,
            retention curves and the Oct 2013 to Oct 2014 movement. Writes results/describe-r1.json.

Usage: python3 -I -B tools/run_study.py <stage> [--data data/enrolments.csv.gz]
"""
import argparse
import csv
import gzip
import hashlib
import json
import os
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
PROTOCOL = json.loads((ROOT / "protocol-r1.json").read_text(encoding="utf-8"))
ASSUME = json.loads((ROOT / "assumptions.json").read_text(encoding="utf-8"))
RES = Path(os.environ.get("TTPR_RESULTS") or ROOT / "results")  # tests point this at a scratch folder
INT = ["id_student", "date_registration", "date_unregistration", "studied_credits", "prev_attempts", "days_active_14",
       "clicks_14", "last_active_14", "days_active_pre", "clicks_pre", "module_length", "first_due_day"]
MISSING = -999999


def load(path, cohorts):
    cols = {}
    with gzip.open(path, "rt", encoding="utf-8", newline="") as f:
        rows = [r for r in csv.DictReader(f) if r["code_presentation"] in cohorts]
    for k in rows[0]:
        if k in INT:
            cols[k] = np.array([MISSING if r[k] == "" else int(r[k]) for r in rows], dtype=np.int64)
        else:
            cols[k] = np.array([r[k] for r in rows])
    return cols


def derived(c):
    """Population masks and signal values, per the protocol's definitions."""
    reg, unreg = c["date_registration"], c["date_unregistration"]
    cancels = unreg != MISSING
    pop = (reg != MISSING) & (reg <= 0) & (~cancels | (unreg >= 14))
    y = cancels & (unreg >= 14)
    last = c["last_active_14"]
    sig = {
        "days_active_14": c["days_active_14"].astype(float),
        "clicks_14": c["clicks_14"].astype(float),
        "days_since_active_14": np.where(last == MISSING, 14, 13 - last).astype(float),
        "days_active_pre": c["days_active_pre"].astype(float),
        "lead_days": np.where(reg == MISSING, np.nan, -reg).astype(float),
        "studied_credits": c["studied_credits"].astype(float),
        "prev_attempts": c["prev_attempts"].astype(float),
    }
    return cancels, pop, y, sig


def direction(name):
    for group in PROTOCOL["signals"].values():
        if name in group:
            return 1.0 if group[name] == "higher_is_riskier" else -1.0
    raise KeyError(name)


def group_of(name):
    return next(g for g, names in PROTOCOL["signals"].items() if name in names)


def ranks(x):
    """Average ranks (1-based), ties share the mean rank."""
    order = np.argsort(x, kind="mergesort")
    xs = x[order]
    r = np.empty(len(x), dtype=float)
    i = 0
    n = len(x)
    # boundaries of tie runs
    edges = np.flatnonzero(np.diff(xs)) + 1
    starts = np.concatenate([[0], edges])
    ends = np.concatenate([edges, [n]])
    avg = (starts + ends + 1) / 2.0
    r[order] = np.repeat(avg, ends - starts)
    return r


def auc(risk, y):
    """Chance a random positive has a higher risk than a random negative, ties counted half."""
    y = y.astype(bool)
    n1, n0 = int(y.sum()), int((~y).sum())
    r = ranks(risk)
    return float((r[y].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0))


def rule_stats(days, y, k):
    flag = days <= k
    n, nf = len(y), int(flag.sum())
    base = y.mean()
    pf = y[flag].mean()
    pr = y[~flag].mean()
    return {"k": int(k), "n": int(n), "flagged": nf, "flag_share": nf / n, "cancel_rate_all": float(base),
            "cancel_rate_flagged": float(pf), "cancel_rate_rest": float(pr), "lift": float(pf / base),
            "rate_ratio_flagged_vs_rest": float(pf / pr), "capture": float(y[flag].sum() / y.sum()),
            "cancellers": int(y.sum()), "cancellers_flagged": int(y[flag].sum())}


def offer(stats):
    """Save-offer arithmetic per 1,000 of the day-14 population, over the declared assumptions."""
    per = PROTOCOL["offer"]["per_n"]
    arms = {"flagged": (per * stats["flag_share"], stats["cancel_rate_flagged"]),
            "everyone": (per, stats["cancel_rate_all"]),
            "random same size": (per * stats["flag_share"], stats["cancel_rate_all"])}
    v, c, s = (ASSUME[k] for k in ("value_of_kept_enrolment_usd", "cost_per_offer_usd", "save_share"))
    out = {}
    for arm, (n, p) in arms.items():
        a = {"offers": n, "cancel_rate_offered": p, "would_cancel_offered": n * p}
        a["kept_at_base"] = n * p * s["base"]
        a["cost_per_kept_base"] = c["base"] / (p * s["base"])
        a["net_base"] = n * (p * s["base"] * v["base"] - c["base"])
        a["break_even_save_share_base"] = c["base"] / (p * v["base"])
        grid = []
        for sv in ("low", "base", "high"):
            for cv in ("low", "base", "high"):
                for vv in ("low", "base", "high"):
                    grid.append({"save_share": s[sv], "cost": c[cv], "value": v[vv],
                                 "net": n * (p * s[sv] * v[vv] - c[cv])})
        a["net_grid"] = grid
        a["net_min"] = min(g["net"] for g in grid)
        a["net_max"] = max(g["net"] for g in grid)
        out[arm] = a
    out["untargeted_over_targeted_cost_per_kept"] = out["everyone"]["cost_per_kept_base"] / out["flagged"]["cost_per_kept_base"]
    better = sum(1 for gf, ge in zip(out["flagged"]["net_grid"], out["everyone"]["net_grid"]) if gf["net"] > ge["net"])
    out["grid_points_flagged_beats_everyone"] = better
    out["grid_points"] = len(out["flagged"]["net_grid"])
    return out


def train(data):
    cohorts = PROTOCOL["cohorts"]["training"]
    c = load(data, set(cohorts))
    assert not set(np.unique(c["code_presentation"])) & set(PROTOCOL["cohorts"]["holdout"])
    cancels, pop, y, sig = derived(c)
    yp = y[pop]
    out = {"stage": "train", "cohorts": cohorts, "enrolments": int(len(y)), "day14_population": int(pop.sum()),
           "left_out_registered_after_day0_or_missing": int(((c["date_registration"] == MISSING) |
                                                              (c["date_registration"] > 0)).sum()),
           "cancelled_before_day14_registered_by_day0": int(((c["date_registration"] != MISSING) &
                                                             (c["date_registration"] <= 0) & cancels &
                                                             (c["date_unregistration"] < 14)).sum()),
           "cancellers_day14_on": int(yp.sum()), "cancel_rate_day14_on": float(yp.mean())}
    rng = np.random.default_rng(PROTOCOL["auc"]["bootstrap_seed"])
    B = PROTOCOL["auc"]["bootstrap_resamples"]
    names = list(sig)
    risk = {n: direction(n) * np.nan_to_num(sig[n][pop], nan=0.0) for n in names}
    point = {n: auc(risk[n], yp) for n in names}
    boots = {n: np.empty(B) for n in names}
    m = len(yp)
    for b in range(B):
        idx = rng.integers(0, m, m)
        for n in names:
            boots[n][b] = auc(risk[n][idx], yp[idx])
    lo, hi = (1 - PROTOCOL["auc"]["interval"]) / 2 * 100, (1 + PROTOCOL["auc"]["interval"]) / 2 * 100
    out["signals"] = {n: {"group": group_of(n), "auc": point[n], "ci": [float(np.percentile(boots[n], lo)),
                                                                          float(np.percentile(boots[n], hi))]}
                      for n in names}
    usage = [n for n in names if group_of(n) == "usage"]
    signup = [n for n in names if group_of(n) == "signup"]
    bu = max(usage, key=lambda n: point[n])
    bs = max(signup, key=lambda n: point[n])
    diff = boots[bu] - boots[bs]
    out["best_usage"], out["best_signup"] = bu, bs
    out["usage_minus_signup_auc"] = point[bu] - point[bs]
    out["usage_minus_signup_ci"] = [float(np.percentile(diff, lo)), float(np.percentile(diff, hi))]
    # the rule
    days = c["days_active_14"][pop]
    shares = {k: float((days <= k).mean()) for k in range(0, 15)}
    target = PROTOCOL["rule"]["target_flag_share"]
    k = min(shares, key=lambda kk: (abs(shares[kk] - target), kk))
    out["flag_share_by_k"] = shares
    out["rule"] = rule_stats(days, yp, k)
    out["rule"]["auc_days_active_14"] = point["days_active_14"]
    out["offer"] = offer(out["rule"])
    # cancel rate by days active, for the evidence table
    out["cancel_rate_by_days_active"] = {str(d): {"n": int((days == d).sum()),
                                                  "cancel_rate": float(yp[days == d].mean()) if (days == d).any() else None}
                                         for d in range(0, 15)}
    RES.mkdir(exist_ok=True)
    rule = {"signal": "days_active_14", "k": k, "form": f"flag when days_active_14 <= {k}",
            "chosen_on": cohorts, "training_flag_share": out["rule"]["flag_share"],
            "training_lift": out["rule"]["lift"], "training_capture": out["rule"]["capture"]}
    write(RES / "rule-r1.json", rule)
    write(RES / "train-r1.json", out)
    print(json.dumps({"k": k, "flag_share": out["rule"]["flag_share"], "lift": out["rule"]["lift"],
                      "capture": out["rule"]["capture"], "best_usage": bu, "best_signup": bs,
                      "diff": out["usage_minus_signup_auc"]}))


def holdout(data):
    rule_path = RES / "rule-r1.json"
    rule_bytes = rule_path.read_bytes()
    rule = json.loads(rule_bytes)
    cohorts = PROTOCOL["cohorts"]["holdout"]
    c = load(data, set(cohorts))
    cancels, pop, y, sig = derived(c)
    yp = y[pop]
    st = rule_stats(c["days_active_14"][pop], yp, rule["k"])
    st["auc_days_active_14"] = auc(-sig["days_active_14"][pop], yp)
    passes = PROTOCOL["holdout_pass"]
    out = {"stage": "holdout", "cohorts": cohorts, "rule_file_sha256": hashlib.sha256(rule_bytes).hexdigest(),
           "rule": rule, "enrolments": int(len(y)), "day14_population": int(pop.sum()), "result": st,
           "lift_ratio": st["lift"] / rule["training_lift"], "capture_ratio": st["capture"] / rule["training_capture"]}
    out["holds"] = bool(out["lift_ratio"] >= passes["lift_ratio_min"] and out["capture_ratio"] >= passes["capture_ratio_min"])
    out["offer"] = offer(st)
    days = c["days_active_14"][pop]
    out["cancel_rate_by_days_active"] = {str(d): {"n": int((days == d).sum()),
                                                  "cancel_rate": float(yp[days == d].mean()) if (days == d).any() else None}
                                         for d in range(0, 15)}
    # per course in the holdout, the same rule
    per = {}
    for mod in sorted(set(c["code_module"][pop])):
        mm = c["code_module"][pop] == mod
        if yp[mm].sum() and (~yp[mm]).sum():
            s = rule_stats(days[mm], yp[mm], rule["k"])
            per[mod] = {"n": s["n"], "flag_share": s["flag_share"], "lift": s["lift"], "capture": s["capture"],
                        "cancel_rate_all": s["cancel_rate_all"]}
    out["by_course"] = per
    write(RES / "holdout-r1.json", out)
    print(json.dumps({"lift": st["lift"], "capture": st["capture"], "lift_ratio": out["lift_ratio"],
                      "capture_ratio": out["capture_ratio"], "holds": out["holds"]}))


def describe(data):
    order = PROTOCOL["cohorts"]["order"]
    c = load(data, set(order))
    cancels, pop, y, sig = derived(c)
    reg, unreg, length = c["date_registration"], c["date_unregistration"], c["module_length"]
    pres = c["code_presentation"]
    out = {"stage": "describe", "cohorts": {}}

    def funnel(mask):
        signed = int(mask.sum())
        reg0 = mask & (reg != MISSING) & (reg <= 0)
        alive = lambda d: int((reg0 & (~cancels | (unreg >= d))).sum())
        due = c["first_due_day"]
        at_due = int((reg0 & (~cancels | (unreg >= due))).sum())
        end = int((reg0 & ~cancels).sum())
        return {"signed_up": signed, "registered_by_day0": int(reg0.sum()),
                "registered_after_day0_or_missing": signed - int(reg0.sum()), "day0": alive(0), "day14": alive(14),
                "first_due": at_due, "end": end}

    def periods(mask):
        reg0 = mask & (reg != MISSING) & (reg <= 0)
        d = unreg[reg0 & cancels]
        out_p = {"before_day0": int((d < 0).sum())}
        top = int(length[mask].max())
        for s in range(0, top + 30, 30):
            out_p[f"{s}-{s + 29}"] = int(((d >= s) & (d <= s + 29)).sum())
        out_p["after_end"] = int((d > length[reg0 & cancels]).sum())
        return out_p

    for p in order + ["all"]:
        mask = np.ones(len(pres), bool) if p == "all" else pres == p
        f = funnel(mask)
        stages = [("signed up to day 0", f["registered_by_day0"] - f["day0"]), ("day 0 to day 14", f["day0"] - f["day14"]),
                  ("day 14 to first assessment", f["day14"] - f["first_due"]), ("first assessment to end", f["first_due"] - f["end"])]
        withdrawn = c["final_result"] == "Withdrawn"
        recon = {"cancel_day_and_withdrawn": int((mask & cancels & withdrawn).sum()),
                 "cancel_day_not_withdrawn": int((mask & cancels & ~withdrawn).sum()),
                 "no_cancel_day_but_withdrawn": int((mask & ~cancels & withdrawn).sum()),
                 "neither": int((mask & ~cancels & ~withdrawn).sum())}
        recon["disagree"] = recon["cancel_day_not_withdrawn"] + recon["no_cancel_day_but_withdrawn"]
        recon["disagree_share"] = recon["disagree"] / int(mask.sum())
        results = {r: int((mask & (c["final_result"] == r)).sum()) for r in ("Pass", "Fail", "Distinction", "Withdrawn")}
        bridge = {"signed_up": int(mask.sum()), "cancelled_before_day0": int((mask & cancels & (unreg < 0)).sum()),
                  "cancelled_day0_13": int((mask & cancels & (unreg >= 0) & (unreg < 14)).sum()),
                  "cancelled_day14_on": int((mask & cancels & (unreg >= 14)).sum()), "stayed": int((mask & ~cancels).sum())}
        bridge["sum_check"] = bridge["cancelled_before_day0"] + bridge["cancelled_day0_13"] + bridge["cancelled_day14_on"] + bridge["stayed"]
        bridge["stayed_vs_pass_fail_distinction"] = bridge["stayed"] - (results["Pass"] + results["Fail"] + results["Distinction"])
        pm = pop & mask
        out["cohorts"][p] = {"funnel": f, "stage_losses": dict(stages),
                             "biggest_loss_stage": max(stages, key=lambda t: t[1])[0], "periods": periods(mask),
                             "reconciliation": recon, "final_results": results, "bridge": bridge,
                             "day14_population": int(pm.sum()), "cancel_rate_day14_on": float(y[pm].mean()),
                             "cancelled_after_end": int((mask & cancels & (unreg > length)).sum())}
    # P4: share of cancellations (registered by day 0) before day 14, all cohorts
    reg0 = (reg != MISSING) & (reg <= 0)
    allc = int((reg0 & cancels).sum())
    early = int((reg0 & cancels & (unreg < 14)).sum())
    out["cancellations_registered_by_day0"] = allc
    out["cancellations_before_day14"] = early
    out["share_before_day14"] = early / allc
    out["share_before_day0"] = int((reg0 & cancels & (unreg < 0)).sum()) / allc
    # retention curves: share of enrolments registered by day 0 not cancelled by day d
    curves = {}
    for p in order:
        m = reg0 & (pres == p)
        dd = unreg[m & cancels]
        nm = int(m.sum())
        curves[p] = {str(d): 1 - float((dd <= d).sum()) / nm for d in range(-60, 271, 10)}
    out["curves"] = curves
    # movement Oct 2013 to Oct 2014, shift-share on the day-14 population
    mv = PROTOCOL["movement"]
    a, b = mv["from"], mv["to"]
    mods = sorted(set(c["code_module"][pop & (pres == a)]) & set(c["code_module"][pop & (pres == b)]))
    def rates(p):
        m = pop & (pres == p)
        tot = int(m.sum())
        return ({mod: float(y[m & (c["code_module"] == mod)].mean()) for mod in mods},
                {mod: int((m & (c["code_module"] == mod)).sum()) / tot for mod in mods}, float(y[m].mean()))
    ra, wa, ta = rates(a)
    rb, wb, tb = rates(b)
    mods_a_all = sorted(set(c["code_module"][pop & (pres == a)]))
    mods_b_all = sorted(set(c["code_module"][pop & (pres == b)]))
    rate_part = sum(wa[m] * (rb[m] - ra[m]) for m in mods)
    mix_part = sum((wb[m] - wa[m]) * rb[m] for m in mods)
    out["movement"] = {"from": a, "to": b, "rate_from": ta, "rate_to": tb, "change": tb - ta,
                       "courses_from": mods_a_all, "courses_to": mods_b_all, "shared_courses": mods,
                       "rate_part_shared": rate_part, "mix_part_shared": mix_part,
                       "by_course": {m: {"rate_from": ra[m], "rate_to": rb[m], "weight_from": wa[m], "weight_to": wb[m]} for m in mods}}
    write(RES / "describe-r1.json", out)
    print(json.dumps({"share_before_day14": out["share_before_day14"], "all": out["cohorts"]["all"]["funnel"],
                      "biggest": out["cohorts"]["all"]["biggest_loss_stage"],
                      "disagree": out["cohorts"]["all"]["reconciliation"]["disagree"],
                      "movement": out["movement"]["change"]}))


def write(path, obj):
    tmp = path.with_suffix(".part")
    tmp.write_text(json.dumps(obj, indent=1, sort_keys=False) + "\n", encoding="utf-8")
    tmp.replace(path)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("stage", choices=["train", "holdout", "describe"])
    ap.add_argument("--data", default=str(ROOT / "data" / "enrolments.csv.gz"))
    a = ap.parse_args()
    {"train": train, "holdout": holdout, "describe": describe}[a.stage](a.data)


if __name__ == "__main__":
    main()
