"""Change 1 (CHANGES-r1.md): the missed first assessment as a later signal, then the holdout of both rules.

  train     training cohorts only: the flag's lift and capture on the later population, the declared day-14 rule on the
            same population, the save-offer arithmetic. Writes results/assess-train-r1.json and assess-rule-r1.json.
  holdout   Oct 2014 only, after both rule files are committed: writes results/assess-holdout-r1.json.

Usage: python3 -I -B tools/run_assessment_signal.py <stage>
"""
import argparse
import csv
import gzip
import hashlib
import json
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, auc, load, offer, rule_stats, write  # noqa: E402

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


def joined(cohorts):
    c = load(ROOT / "data" / "enrolments.csv.gz", set(cohorts))
    fa = {}
    with gzip.open(ROOT / "data" / "first-assessment.csv.gz", "rt", encoding="utf-8", newline="") as f:
        for r in csv.DictReader(f):
            if r["code_presentation"] in cohorts:
                fa[(r["code_module"], r["code_presentation"], int(r["id_student"]))] = r
    keys = zip(c["code_module"], c["code_presentation"], c["id_student"])
    rows = [fa[(m, p, int(s))] for m, p, s in keys]
    due = np.array([int(r["first_due_day"]) for r in rows])
    subd = np.array([MISSING if r["submitted_day"] == "" else int(r["submitted_day"]) for r in rows])
    banked = np.array([r["is_banked"] == "1" for r in rows])
    assert (due == c["first_due_day"]).all()
    return c, due, subd, banked


def measure(cohorts, k_day14):
    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]
    on_time = banked | ((subd != MISSING) & (subd <= due))
    missed = (~on_time)[pop]
    # rule_stats flags values <= k: pass 0 for missed, 1 for handed in, and k = 0
    st = rule_stats(np.where(missed, 0, 1), y, 0)
    st["auc_flag"] = auc(missed.astype(float), y)
    d14 = rule_stats(c["days_active_14"][pop], y, k_day14)
    reg0 = (reg != MISSING) & (reg <= 0)
    before = int((reg0 & cancels & (unreg <= due)).sum())
    allc = int((reg0 & cancels).sum())
    return {"cohorts": cohorts, "enrolments": int(len(reg)), "population": int(pop.sum()), "flag": st,
            "day14_rule_same_population": d14, "offer": offer(st),
            "cancellations_on_or_before_due_registered_by_day0": before,
            "cancellations_registered_by_day0": allc, "share_cancellations_before_signal": before / allc,
            "due_days": sorted(set(int(x) for x in due))}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("stage", choices=["train", "holdout"])
    a = ap.parse_args()
    rule14 = json.loads((RES / "rule-r1.json").read_text(encoding="utf-8"))
    if a.stage == "train":
        out = measure(PROTOCOL["cohorts"]["training"], rule14["k"])
        out["stage"] = "train"
        rule = {"signal": "missed first assessment",
                "form": "flag when the first marked assignment was not handed in by its due day",
                "chosen_on": PROTOCOL["cohorts"]["training"], "training_flag_share": out["flag"]["flag_share"],
                "training_lift": out["flag"]["lift"], "training_capture": out["flag"]["capture"]}
        write(RES / "assess-rule-r1.json", rule)
        write(RES / "assess-train-r1.json", out)
        print(json.dumps({"flag_share": out["flag"]["flag_share"], "lift": out["flag"]["lift"],
                          "capture": out["flag"]["capture"],
                          "d14_lift_same_pop": out["day14_rule_same_population"]["lift"],
                          "share_before_signal": out["share_cancellations_before_signal"]}))
    else:
        rb = (RES / "assess-rule-r1.json").read_bytes()
        rule = json.loads(rb)
        out = measure(PROTOCOL["cohorts"]["holdout"], rule14["k"])
        out["stage"] = "holdout"
        out["rule_file_sha256"] = hashlib.sha256(rb).hexdigest()
        out["lift_ratio"] = out["flag"]["lift"] / rule["training_lift"]
        out["capture_ratio"] = out["flag"]["capture"] / rule["training_capture"]
        p = PROTOCOL["holdout_pass"]
        out["holds"] = bool(out["lift_ratio"] >= p["lift_ratio_min"] and out["capture_ratio"] >= p["capture_ratio_min"])
        write(RES / "assess-holdout-r1.json", out)
        print(json.dumps({"lift": out["flag"]["lift"], "capture": out["flag"]["capture"],
                          "lift_ratio": out["lift_ratio"], "capture_ratio": out["capture_ratio"],
                          "holds": out["holds"]}))


if __name__ == "__main__":
    main()
