"""Change 2 (CHANGES-r2.md): checks added after the results. Writes results/change2-r2.json.

The same-day use rule's cut is chosen on the training cohorts only, before Oct 2014 is scored. Nothing here rewrites a
frozen result; the frozen rule files are read and their sha256 recorded.

Usage: python3 -I -B tools/run_change2.py
"""
import csv
import gzip
import hashlib
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 ASSUME, MISSING, PROTOCOL, RES, auc, write  # noqa: E402
from run_assessment_signal import joined  # noqa: E402

ROOT = Path(__file__).resolve().parent.parent
TRAIN, HOLD = PROTOCOL["cohorts"]["training"], PROTOCOL["cohorts"]["holdout"]
CUTS = [round(0.05 * i, 2) for i in range(21)]


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


def first_types():
    t = {}
    with gzip.open(ROOT / "data" / "first-assessment.csv.gz", "rt", encoding="utf-8", newline="") as f:
        for r in csv.DictReader(f):
            t[(r["code_module"], r["code_presentation"])] = r["first_assessment_type"]
    return t


def due_usage(cohorts):
    u = {}
    with gzip.open(ROOT / "data" / "due-usage.csv.gz", "rt", encoding="utf-8", newline="") as f:
        for r in csv.DictReader(f):
            if r["code_presentation"] in cohorts:
                u[(r["code_module"], r["code_presentation"], int(r["id_student"]))] = int(r["days_active_to_due"])
    return u


def frame(cohorts):
    """The frozen due-day group of change 1, with the flag, the outcome, the run, its first test's type and use share."""
    c, due, subd, banked = joined(cohorts)
    reg, unreg = c["date_registration"], c["date_unregistration"]
    cancels = unreg != MISSING
    pop = (reg != MISSING) & (reg <= 0) & (~cancels | (unreg > due))
    y = (cancels & (unreg > due))[pop]
    missed = (~(banked | ((subd != MISSING) & (subd <= due))))[pop]
    types = first_types()
    runs = np.array([f"{m} {p}" for m, p in zip(c["code_module"], c["code_presentation"])])[pop]
    tutor = np.array([types[(m, p)] == "TMA" for m, p in zip(c["code_module"], c["code_presentation"])])[pop]
    u = due_usage(cohorts)
    active = np.array([u[(m, p, int(s))] for m, p, s in zip(c["code_module"], c["code_presentation"], c["id_student"])])
    share = (active / (due + 1))[pop]
    assert set(c["code_presentation"]) <= set(cohorts)
    reg0 = (reg != MISSING) & (reg <= 0)
    reach = {"cancellations_registered_by_day0": int((reg0 & cancels).sum()),
             "on_or_before_first_due_day": int((reg0 & cancels & (unreg <= due)).sum())}
    reach["share_out_of_reach"] = reach["on_or_before_first_due_day"] / reach["cancellations_registered_by_day0"]
    return {"y": y, "missed": missed, "runs": runs, "tutor": tutor, "share": share, "reach": reach,
            "course": np.array([r.split()[0] for r in runs])}


def by_course(f):
    out = {}
    for run in sorted(set(f["runs"])):
        m = f["runs"] == run
        st = stats(f["missed"][m], f["y"][m])
        st["first_test_tutor_marked"] = bool(f["tutor"][m][0])
        out[run] = st
    return out


def change2():
    tr = frame(TRAIN)
    # C-C: the cut is chosen here, on training tutor-marked runs only, before Oct 2014 is read
    t = tr["tutor"]
    target = float(tr["missed"][t].mean())
    shares = {cut: float((tr["share"][t] <= cut + 1e-12).mean()) for cut in CUTS}
    cut = min(CUTS, key=lambda k: (abs(shares[k] - target), k))
    ho = frame(HOLD)
    rule_files = {n: hashlib.sha256((RES / n).read_bytes()).hexdigest() for n in ("rule-r1.json", "assess-rule-r1.json")}
    res = {"declared_in": "CHANGES-r2.md", "frozen_rule_files_sha256": rule_files, "cohorts": {"training": TRAIN,
                                                                                               "holdout": HOLD}}
    res["C-A_by_course_run"] = {"training": by_course(tr), "holdout": by_course(ho)}
    cb = {}
    for name, f in (("training", tr), ("holdout", ho)):
        t = f["tutor"]
        cb[name] = stats(f["missed"][t], f["y"][t])
        cb[name]["runs"] = sorted(set(f["runs"][t]))
        cb[name]["runs_left_out"] = sorted(set(f["runs"][~t]))
    cb["lift_ratio"] = cb["holdout"]["lift"] / cb["training"]["lift"]
    cb["capture_ratio"] = cb["holdout"]["capture"] / cb["training"]["capture"]
    p = PROTOCOL["holdout_pass"]
    cb["holds"] = bool(cb["lift_ratio"] >= p["lift_ratio_min"] and cb["capture_ratio"] >= p["capture_ratio_min"])
    res["C-B_tutor_marked_runs"] = cb
    cc = {"cut": cut, "target_flag_share": target, "flag_share_by_cut_training": {str(k): v for k, v in shares.items()}}
    for name, f in (("training", tr), ("holdout", ho)):
        t = f["tutor"]
        use = stats(f["share"][t] <= cut + 1e-12, f["y"][t])
        use["auc_use_share"] = auc(-f["share"][t], f["y"][t])
        flag = cb[name]
        cc[name] = {"use_rule": use, "assignment_flag_lift": flag["lift"],
                    "assignment_flag_auc": auc(f["missed"][t].astype(float), f["y"][t]),
                    "lift_gap": flag["lift"] - use["lift"]}
    res["C-C_same_day_use"] = cc
    allc = frame(TRAIN + HOLD)["reach"]
    res["C-D_reach"] = {"training": tr["reach"], "holdout": ho["reach"], "all_four": allc}
    # C-E: the frozen sizing, its precision and its readout time
    after = json.loads((RES / "after-r1.json").read_text(encoding="utf-8"))
    ts = after["test_size"]
    p1 = ts["base_cancel_rate_flagged"]
    s10 = ts["by_save_share"]["0.1"]
    p2, n = s10["cancel_rate_offered"], s10["per_arm"]
    var = p1 * (1 - p1) + p2 * (1 - p2)
    hw = 1.96 * math.sqrt(var / n)
    v, cst = ASSUME["value_of_kept_enrolment_usd"]["base"], ASSUME["cost_per_offer_usd"]["base"]
    be = cst / v
    drop = p1 - p2
    need = math.ceil((1.959964 + 0.841621) ** 2 * var / (drop - be) ** 2)
    enr = {}
    with gzip.open(ROOT / "data" / "enrolments.csv.gz", "rt", encoding="utf-8", newline="") as f:
        for r in csv.DictReader(f):
            if r["code_presentation"] in ("2014B", "2014J"):
                enr[r["code_presentation"]] = max(enr.get(r["code_presentation"], 0), int(r["module_length"]))
    flagged = {"B": ts["flagged_feb_2014"], "J": ts["flagged_oct_2014"]}
    length = {"B": enr["2014B"], "J": enr["2014J"]}
    gap = {"B": 8, "J": 4}  # months from a Feb start to the Oct one, and from Oct to the next Feb
    plans = {}
    for start in ("B", "J"):
        got, month, k, seq = 0, 0, start, []
        while True:
            got += flagged[k]
            seq.append(k)
            if got >= s10["total"]:
                break
            month += gap[k]
            k = "J" if k == "B" else "B"
        plans["Feb start" if start == "B" else "Oct start"] = {
            "cohorts_needed": len(seq), "flagged_enrolled": got, "months_to_last_start": month,
            "months_to_readout": month + length[k] / (365.25 / 12)}
    res["C-E_test"] = {"per_half": n, "total": s10["total"], "cancel_rate_control": p1, "cancel_rate_called": p2,
                       "sized_drop_points": 100 * drop, "interval_half_width_points": 100 * hw,
                       "break_even_drop_points": 100 * be, "smallest_drop_clearing_break_even_points": 100 * (be + hw),
                       "per_half_to_clear_break_even_at_sized_drop": need, "course_length_days": length,
                       "readout": plans}
    at = json.loads((RES / "assess-train-r1.json").read_text(encoding="utf-8"))
    fl = at["flag"]
    res["C-F_equal_effect"] = {"min_save_share_ratio_flagged_to_rest": fl["cancel_rate_rest"] / fl["cancel_rate_flagged"]}
    grid_f, grid_e = at["offer"]["flagged"]["net_grid"], at["offer"]["everyone"]["net_grid"]
    res["grid_points_everyone_nets_more"] = [{k: gf[k] for k in ("save_share", "cost", "value")}
                                            for gf, ge in zip(grid_f, grid_e) if ge["net"] > gf["net"]]
    res["predictions"] = {
        "Q1": {"training_lift": cb["training"]["lift"], "holds_on_holdout": cb["holds"],
               "held": bool(cb["training"]["lift"] >= 1.5 and cb["holds"])},
        "Q2": {"gap_training": cc["training"]["lift_gap"], "gap_holdout": cc["holdout"]["lift_gap"],
               "held": bool(cc["training"]["lift_gap"] >= 0.20 and cc["holdout"]["lift_gap"] >= 0.20)},
    }
    within = {r: s for r, s in res["C-A_by_course_run"]["holdout"].items() if s["first_test_tutor_marked"]}
    res["predictions"]["Q3"] = {"courses": len(within),
                                "at_least_1_3": sum(1 for s in within.values() if s["lift"] is not None and s["lift"] >= 1.3),
                                "lifts": {r: s["lift"] for r, s in within.items()}}
    res["predictions"]["Q3"]["held"] = bool(res["predictions"]["Q3"]["at_least_1_3"] >= 5)
    return res


def main():
    res = change2()
    write(RES / "change2-r2.json", res)
    print(json.dumps({"Q": {k: v["held"] for k, v in res["predictions"].items()},
                      "C-B": {k: res["C-B_tutor_marked_runs"][k]["lift"] for k in ("training", "holdout")},
                      "C-C cut": res["C-C_same_day_use"]["cut"],
                      "C-C gaps": [res["C-C_same_day_use"][k]["lift_gap"] for k in ("training", "holdout")]}))


if __name__ == "__main__":
    main()
