"""Figures added after the results, each labelled so on the pages. Reads the frozen data and rule files only.

  1. The Oct 2013 to Oct 2014 movement split three ways: rates within the six courses both cohorts share, their mix,
     and the course that was new in Oct 2014.
  2. A sensitivity check: count an enrolment as cancelled when either table says so (the results table marks some
     enrolments Withdrawn that have no cancellation day), and rescore both rules on the Oct 2014 holdout.
  3. The size of a randomised test of the save offer among the flagged, and how many flagged enrolments a year brings.

Usage: python3 -I -B tools/after_results.py   (writes results/after-r1.json)
"""
import json
import math
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from run_study import MISSING, PROTOCOL, RES, load, rule_stats, write  # noqa: E402
from run_assessment_signal import joined  # noqa: E402

ROOT = Path(__file__).resolve().parent.parent


def movement():
    c = load(ROOT / "data" / "enrolments.csv.gz", {"2013J", "2014J"})
    reg, unreg = c["date_registration"], c["date_unregistration"]
    cancels = unreg != MISSING
    pop = (reg != MISSING) & (reg <= 0) & (~cancels | (unreg >= 14))
    y = cancels & (unreg >= 14)
    pres, mod = c["code_presentation"], c["code_module"]
    a, b = pop & (pres == "2013J"), pop & (pres == "2014J")
    shared = sorted(set(mod[a]) & set(mod[b]))
    new = sorted(set(mod[b]) - set(mod[a]))
    bs = b & np.isin(mod, shared)
    rate_a, rate_b, rate_b_shared = float(y[a].mean()), float(y[b].mean()), float(y[bs].mean())
    wa = {m: float((a & (mod == m)).sum() / a.sum()) for m in shared}
    wbs = {m: float((bs & (mod == m)).sum() / bs.sum()) for m in shared}
    ra = {m: float(y[a & (mod == m)].mean()) for m in shared}
    rb = {m: float(y[bs & (mod == m)].mean()) for m in shared}
    within = sum(wa[m] * (rb[m] - ra[m]) for m in shared)
    mix = sum((wbs[m] - wa[m]) * rb[m] for m in shared)
    newc = {m: {"n": int((b & (mod == m)).sum()), "rate": float(y[b & (mod == m)].mean()),
                "share_of_cohort": float((b & (mod == m)).sum() / b.sum())} for m in new}
    out = {"from": "2013J", "to": "2014J", "rate_from": rate_a, "rate_to": rate_b, "change": rate_b - rate_a,
           "rate_to_shared_courses_only": rate_b_shared, "shared_courses": shared, "new_courses": newc,
           "within_shared": within, "mix_shared": mix, "new_course_part": rate_b - rate_b_shared}
    assert abs(within + mix - (rate_b_shared - rate_a)) < 1e-12
    assert abs(out["within_shared"] + out["mix_shared"] + out["new_course_part"] - out["change"]) < 1e-12
    return out


def sensitivity():
    rule14 = json.loads((RES / "rule-r1.json").read_text(encoding="utf-8"))
    c, due, subd, banked = joined(PROTOCOL["cohorts"]["holdout"])
    reg, unreg = c["date_registration"], c["date_unregistration"]
    withdrawn_no_day = (unreg == MISSING) & (c["final_result"] == "Withdrawn")
    cancels = unreg != MISSING
    out = {"withdrawn_without_cancel_day": int(withdrawn_no_day.sum())}
    # day-14 rule: those enrolments are in the day-14 population already (no cancellation day); count them as later cancellers
    pop14 = (reg != MISSING) & (reg <= 0) & (~cancels | (unreg >= 14))
    y14 = ((cancels & (unreg >= 14)) | withdrawn_no_day)[pop14]
    out["day14_rule"] = rule_stats(c["days_active_14"][pop14], y14, rule14["k"])
    popd = (reg != MISSING) & (reg <= 0) & (~cancels | (unreg > due))
    yd = ((cancels & (unreg > due)) | withdrawn_no_day)[popd]
    on_time = banked | ((subd != MISSING) & (subd <= due))
    out["missed_first_assessment"] = rule_stats(np.where((~on_time)[popd], 0, 1), yd, 0)
    out["in_population_day14"] = int((withdrawn_no_day & pop14).sum())
    return out


def test_size():
    """Two-arm test among the flagged: offer against no offer, two-sided 5%, power 80%."""
    h = json.loads((RES / "assess-holdout-r1.json").read_text(encoding="utf-8"))
    tr = json.loads((RES / "assess-train-r1.json").read_text(encoding="utf-8"))
    p1 = h["flag"]["cancel_rate_flagged"]
    za, zb = 1.959963984540054, 0.8416212335729143
    out = {"base_cancel_rate_flagged": p1, "alpha_two_sided": 0.05, "power": 0.8, "by_save_share": {}}
    for s in (0.05, 0.10, 0.20):
        p2 = p1 * (1 - s)
        n = (za + zb) ** 2 * (p1 * (1 - p1) + p2 * (1 - p2)) / (p1 - p2) ** 2
        out["by_save_share"][str(s)] = {"cancel_rate_offered": p2, "drop_points": 100 * (p1 - p2),
                                        "per_arm": math.ceil(n), "total": 2 * math.ceil(n)}
    # flagged a year: the two latest cohorts (Feb 2014 from training, Oct 2014 from the holdout)
    c, due, subd, banked = joined(["2014B"])
    reg, unreg = c["date_registration"], c["date_unregistration"]
    cancels = unreg != MISSING
    pop = (reg != MISSING) & (reg <= 0) & (~cancels | (unreg > due))
    on_time = banked | ((subd != MISSING) & (subd <= due))
    feb = int(((~on_time) & pop).sum())
    out["flagged_feb_2014"] = feb
    out["flagged_oct_2014"] = h["flag"]["flagged"]
    out["flagged_a_year"] = feb + h["flag"]["flagged"]
    out["flagged_training_three_cohorts"] = tr["flag"]["flagged"]
    return out


def main():
    out = {"note": "Added after the results. Each figure is labelled so wherever a page uses it.",
           "movement": movement(), "sensitivity_holdout": sensitivity(), "test_size": test_size()}
    write(RES / "after-r1.json", out)
    m, s, t = out["movement"], out["sensitivity_holdout"], out["test_size"]
    print(json.dumps({"change": m["change"], "shared_only": m["rate_to_shared_courses_only"], "within": m["within_shared"],
                      "mix": m["mix_shared"], "new": m["new_course_part"], "new_courses": m["new_courses"],
                      "sens_d14_lift": s["day14_rule"]["lift"], "sens_flag_lift": s["missed_first_assessment"]["lift"],
                      "sens_flag_capture": s["missed_first_assessment"]["capture"], "wnd": s["withdrawn_without_cancel_day"],
                      "n10": t["by_save_share"]["0.1"], "year": t["flagged_a_year"]}))


if __name__ == "__main__":
    main()
