"""Change 3 (declared in CHANGES-r3.md, which is not published; the method page gives what it says): the value of a kept enrolment at which calling everyone nets as much as calling only the
students who missed the first assignment. Arithmetic on the frozen offer results and assumptions; writes
results/change3-r3.json. No frozen file is changed.

Usage: python3 -I -B tools/run_change3.py
"""
import hashlib
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from run_study import ASSUME, RES, write  # noqa: E402


def break_even(offer, cost, save):
    f, ev = offer["flagged"], offer["everyone"]
    extra_calls = ev["offers"] - f["offers"]
    extra_kept = save * (ev["would_cancel_offered"] - f["would_cancel_offered"])
    return cost * extra_calls / extra_kept


def change3():
    c, s = ASSUME["cost_per_offer_usd"], ASSUME["save_share"]
    out = {"declared_in": "CHANGES-r3.md", "per": "1,000 students enrolled on the first due day",
           # taken from the university's fees page (archived copy, cleaned text); not used in any sum
           "fee_page": {"gbp_30_credits": 1316, "gbp_60_credits": 2632,
                        "for": "modules starting from August 2014, students in England"}}
    for name, fname in (("training", "assess-train-r1.json"), ("holdout", "assess-holdout-r1.json")):
        raw = (RES / fname).read_bytes()
        offer = json.loads(raw.decode("utf-8"))["offer"]
        base = break_even(offer, c["base"], s["base"])
        # the published base-case nets must cross at this value: check it against the frozen per-kept arithmetic
        f, ev = offer["flagged"], offer["everyone"]
        net_f = base * s["base"] * f["would_cancel_offered"] - c["base"] * f["offers"]
        net_e = base * s["base"] * ev["would_cancel_offered"] - c["base"] * ev["offers"]
        assert abs(net_f - net_e) < 1e-6
        grid = [{"cost": cost, "save_share": save, "break_even_value": break_even(offer, cost, save)}
                for save in (s["low"], s["base"], s["high"]) for cost in (c["low"], c["base"], c["high"])]
        out[name] = {"source_sha256": hashlib.sha256(raw).hexdigest(), "break_even_value_at_base": base,
                     "net_both_at_break_even": net_f, "grid": grid}
    return out


def main():
    res = change3()
    write(RES / "change3-r3.json", res)
    print(json.dumps({k: round(res[k]["break_even_value_at_base"], 1) for k in ("training", "holdout")}))


if __name__ == "__main__":
    main()
