"""Change 1, added after the results were seen: the checks declared in change-1-public.json. Writes results/change-1.json.

The frozen results are read and never written. Every figure here is labelled on the page as added after the results.

Usage: python3 -I -B tools/change_1.py <cells-change-1.json>   needs the aggregated cells, adds the whole-department intervals
       python3 -I -B tools/change_1.py --replay                recomputes every point estimate from the public results alone
"""
import json
import os
import sys

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE)
import bunching as bu  # noqa: E402

SEED, REPS = 20191002, 400
FIGS = bu.ALWAYS
KEYS = ("G|before", "G|after", "S|before", "S|after")
SETTINGS = ((7, 2500), (3, 2500), (5, 2500), (9, 2500), (7, 1500), (7, 5000))
SWEEP = (1.0, 1.5, 2.0, 2.5)
MASK_BELOW = 5
WINDOWS = {f: (bu.window_bins(f, True), bu.window_bins(f, False)) for f in FIGS}
TOP = {f: list(bu.EDGES).index(f) for f in FIGS}
NO_LIMIT = (("G", "before", 40000), ("G", "after", 40000), ("G", "before", 100000), ("G", "after", 100000),
            ("S", "before", 40000), ("S", "after", 25000))


def load(name):
    with open(os.path.join(ROOT, name), encoding="utf-8") as f:
        return json.load(f)


def at_figures(y, degree=7):
    """E, H and B at the three limit figures from one fit. The same numbers as bunching.measures, without refitting."""
    y = np.asarray(y, dtype=float)
    cf, mult = bu.fit(y, FIGS, degree)
    out = {}
    for f, (below, above) in WINDOWS.items():
        obs_b, cf_b, obs_a, cf_a = y[below].sum(), cf[below].sum(), y[above].sum(), cf[above].sum()
        out[f] = {"E": float(obs_b / cf_b), "H": float(obs_a / cf_a), "B": float(obs_b - cf_b), "obs": float(obs_b),
                  "cf_window": float(cf_b), "cf_top": float(cf[TOP[f]]), "missing_above": float(cf_a - obs_a)}
    return out, mult


def natural(cells):
    """D40 and D25 from E values keyed like cells["S|after"][40000]["E"]."""
    d = lambda g, f: cells[f"{g}|after"][f]["E"] - cells[f"{g}|before"][f]["E"]
    return {"D40": d("S", 40000) - d("G", 40000), "D25": d("S", 25000) - d("G", 25000)}


def e_with_multiplier(m, old, new):
    """E with one figure's round multiplier set to another value, holding the curve."""
    return m["obs"] / (m["cf_window"] - m["cf_top"] + m["cf_top"] * new / old)


def placebo_rule(cell, placebos, e_value, ci, figure):
    """The declared labelling rule on one cell, given that cell's placebos."""
    cls = bu.round_class(figure)
    same = [v for r, v in placebos.items() if bu.round_class(int(r)) == cls]
    return {"label": bu.label_limit(e_value, ci, same, list(placebos.values())), "max_same_class": max(same) if same else None,
            "p90_all": float(np.percentile(list(placebos.values()), 90))}


def points(summary, hist, counts):
    """Everything computable from the public results and the public counts of this change."""
    ys = {k: np.array(v["n"], dtype=float) for k, v in hist["cells"].items()}
    base = {k: at_figures(ys[k]) for k in KEYS}
    out = {}

    # B: the labelling rule on cells with no limit
    out["B_rule_on_cells_with_no_limit"] = {}
    for g, p, f in NO_LIMIT:
        cell = f"{g}|{p}"
        pl = {r: v["E"] for r, v in summary["points"]["placebos"][cell].items()}
        trimmed = {r: v for r, v in pl.items() if r not in ("15000", "20000")}
        e_v, ci = summary["points"]["cells"][cell]["figures"][str(f)]["E"], summary["intervals"][f"{cell}|{f}|E"]
        out["B_rule_on_cells_with_no_limit"][f"{cell}|{f}"] = {"E": e_v, "interval": ci, "declared_placebos": placebo_rule(cell, pl, e_v, ci, f),
                                                               "without_15000_and_20000": placebo_rule(cell, trimmed, e_v, ci, f)}

    # C: the coverage rule as written
    out["C_coverage_rule_as_written"] = {}
    for name in ("before_from_2000", "before_from_2016"):
        cells = {k: base[k][0] for k in KEYS}
        for g in ("G", "S"):
            y = np.array(counts[name][g], dtype=float)
            cells[f"{g}|before"] = at_figures(y)[0]
        out["C_coverage_rule_as_written"][name] = {
            "n": {g: int(sum(counts[name][g])) for g in ("G", "S")},
            "E_S_before": {str(f): cells["S|before"][f]["E"] for f in FIGS}, "E_G_before": {str(f): cells["G|before"][f]["E"] for f in FIGS},
            **natural(cells)}

    # D: round prices with tax removed
    out["D_round_prices_removed"] = {}
    for tier in ("no_round_1000", "no_round_100"):
        ty = {k: np.array(counts[tier][k], dtype=float) for k in KEYS}
        fits = {k: at_figures(ty[k]) for k in KEYS}
        rec = {"cells": {k: {"n": int(ty[k].sum()), "multipliers": fits[k][1],
                             "figures": {str(f): {m: fits[k][0][f][m] for m in ("E", "H", "B", "missing_above")} for f in FIGS}} for k in KEYS}}
        rec.update(natural({k: fits[k][0] for k in KEYS}))
        rec["placebo_115000"] = {k: bu.measures(ty[k], 115000)["E"] for k in KEYS}
        placebos = {str(r): bu.measures(ty["S|after"], r)["E"] for r in bu.PLACEBOS if r not in (15000, 20000)}
        rec["placebos_services_after"] = {"max": max(placebos.values()), "max_figure": max(placebos, key=placebos.get),
                                          "above_1_2": sum(1 for v in placebos.values() if v > 1.2), "n": len(placebos)}
        out["D_round_prices_removed"][tier] = rec

    # E: the round-class sweep and the 10000 multiplier held
    sweep = {}
    for f, cls in ((25000, "k25"), (100000, "k50")):
        sweep[str(f)] = {}
        for new in SWEEP:
            es = {k: e_with_multiplier(base[k][0][f], base[k][1][cls], new) for k in KEYS}
            rec = {"E": es}
            if f == 25000:
                rec["D25"] = (es["S|after"] - es["S|before"]) - (es["G|after"] - es["G|before"])
            sweep[str(f)][str(new)] = rec
    held = {k: base[k][0][40000]["E"] for k in KEYS}
    held["S|after"] = e_with_multiplier(base["S|after"][0][40000], base["S|after"][1]["k10"], base["S|before"][1]["k10"])
    held["G|after"] = e_with_multiplier(base["G|after"][0][40000], base["G|after"][1]["k10"], base["G|before"][1]["k10"])
    out["E_round_class_sweep"] = {
        "bins_learning_each_class": {"k25": [75000, 125000], "k50": [50000, 150000]},
        "fitted": {k: {c: base[k][1][c] for c in ("k10", "k25", "k50")} for k in KEYS}, "sweep": sweep,
        "k10_held_at_before": {"E": held, "D40": (held["S|after"] - held["S|before"]) - (held["G|after"] - held["G|before"])}}

    # F: the excess count across the six settings
    window_vals = [i for i, x in enumerate(bu.EDGES) if 37500 < x <= 40000]
    cell = hist["cells"]["S|after"]
    mean_value = sum(cell["value_sum"][i] for i in window_vals) / sum(cell["n"][i] for i in window_vals)
    b = {}
    for degree, window in SETTINGS:
        bu.WINDOW = window
        b[f"degree {degree}, window {window}"] = bu.measures(ys["S|after"], 40000, degree=degree)["B"]
        bu.WINDOW = 2500
    out["F_excess_count"] = {"B": b, "mean_value_in_window": mean_value}

    # G: placebos inside each public body
    dept = {}
    figures = [r for r in bu.PLACEBOS if r >= 30000]
    for org, arr in hist["departments_services_after"]["counts"].items():
        y = np.array(arr, dtype=float)
        ms = {str(r): bu.measures(y, r, degree=3) for r in figures}
        vals = {r: m["E"] for r, m in ms.items()}
        e_v = summary["points"]["departments"][org]["E"]
        dept[org] = {"title": hist["departments_services_after"]["titles"][org], "E": e_v, "highest_placebo": max(vals.values()),
                     "highest_figure": max(vals, key=vals.get), "highest_observed": ms[max(vals, key=vals.get)]["observed_below"], "above_1_2": sum(1 for v in vals.values() if v > 1.2), "n": len(vals)}
    out["G_department_placebos"] = dept

    # H: the yardstick without the two figures at the edge of the fit
    yard = {}
    for c in KEYS:
        vals = {r: v["E"] for r, v in summary["points"]["placebos"][c].items() if r not in ("15000", "20000")}
        yard[c] = {"max": max(vals.values()), "max_figure": max(vals, key=vals.get), "p90": float(np.percentile(list(vals.values()), 90)),
                   "above_1_2": sum(1 for v in vals.values() if v > 1.2), "n": len(vals)}
    out["H_yardstick_without_15000_and_20000"] = yard
    return out


def public_counts(doc):
    """Sum the aggregated cells to the public counts. Nothing below a whole cell is kept."""
    n = bu.N_BINS
    counts = {"no_round_1000": {}, "no_round_100": {}, "before_from_2000": {}, "before_from_2016": {}}
    for tier in ("no_round_1000", "no_round_100"):
        counts[tier] = {f"{g}|{p}": [0] * n for g in ("G", "S", "C") for p in ("before", "after")}
    for name in ("before_from_2000", "before_from_2016"):
        counts[name] = {g: [0] * n for g in ("G", "S", "C")}
    for key, c in doc["cells"].items():
        _, _, g, p = key.split("|")
        if p in ("before", "after"):
            for tier in ("no_round_1000", "no_round_100"):
                for si, v in c.get(tier, {}).items():
                    counts[tier][f"{g}|{p}"][int(si)] += v
        if p in ("before", "fy2016", "fy2000_2015"):
            for si, v in c["n"].items():
                counts["before_from_2000"][g][int(si)] += v
                if p != "fy2000_2015":
                    counts["before_from_2016"][g][int(si)] += v
    return counts


def mask(v):
    return v if v >= MASK_BELOW else f"under {MASK_BELOW}"


def public_makeup(doc):
    """The makeup of the top bins and the counts at each limit plus tax, small counts masked."""
    makeup = {}
    for cell, figs in doc["makeup_of_top_bins"].items():
        makeup[cell] = {}
        for f, m in figs.items():
            at_1000, at_100 = sum(m["at_tier_1000_by_rate"].values()), sum(m["at_tier_100_by_rate"].values())
            makeup[cell][f] = {"n": m["n"], "round_priced_tier_1000": at_1000, "round_priced_tier_100": at_100,
                               "share_tier_1000": at_1000 / m["n"], "share_tier_100": at_100 / m["n"],
                               "tier_1000_by_tax_rate": {r: mask(v) for r, v in sorted(m["at_tier_1000_by_rate"].items(), key=lambda x: int(x[0]))}}
    shadows = {cell: {k: mask(v) for k, v in sorted(s.items(), key=lambda x: tuple(int(p) for p in x[0].split("|")))}
               for cell, s in doc["shadows"].items()}
    return makeup, shadows


def bootstrap(doc, rng):
    """Whole-department bootstrap, one shared draw per replicate across all the readings."""
    orgs = sorted({k.split("|")[0] for k in doc["cells"] if k.split("|")[2] in ("G", "S")})
    index = {o: i for i, o in enumerate(orgs)}
    n = bu.N_BINS
    mats = {name: {k: np.zeros((len(orgs), n)) for k in KEYS} for name in ("all", "no_round_1000", "from_2000", "from_2016")}
    for key, c in doc["cells"].items():
        org, _, g, p = key.split("|")
        if g not in ("G", "S"):
            continue
        row = index[org]
        for si, v in c["n"].items():
            i = int(si)
            if p in ("before", "after"):
                mats["all"][f"{g}|{p}"][row, i] += v
            if p == "after":
                mats["from_2000"][f"{g}|after"][row, i] += v
                mats["from_2016"][f"{g}|after"][row, i] += v
            if p in ("before", "fy2016", "fy2000_2015"):
                mats["from_2000"][f"{g}|before"][row, i] += v
            if p in ("before", "fy2016"):
                mats["from_2016"][f"{g}|before"][row, i] += v
        if p in ("before", "after"):
            for si, v in c.get("no_round_1000", {}).items():
                mats["no_round_1000"][f"{g}|{p}"][row, int(si)] += v
    runs = {name: {} for name in mats}
    for _ in range(REPS):
        w = rng.multinomial(len(orgs), np.full(len(orgs), 1 / len(orgs)))[:, None]
        fits = {}
        for name, cells in mats.items():
            res = {}
            for k, mat in cells.items():
                if name in ("from_2000", "from_2016") and k.endswith("after"):
                    res[k] = fits["all"][k]
                else:
                    res[k] = at_figures((mat * w).sum(axis=0))[0]
            fits[name] = res
            store = runs[name]
            if name in ("all", "no_round_1000"):
                for k in KEYS:
                    for f in FIGS:
                        for m in ("E", "H", "B"):
                            store.setdefault(f"{k}|{f}|{m}", []).append(res[k][f][m])
            for dname, v in natural(res).items():
                store.setdefault(dname, []).append(v)
    cis = {name: {k: [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] for k, v in store.items()} for name, store in runs.items()}
    return cis, len(orgs)


def score(pts, cis, makeup, summary):
    a, d = cis["all"], pts["D_round_prices_removed"]
    width = lambda i: i[1] - i[0]
    tier = d["no_round_1000"]
    d25_sweep = [v["D25"] for v in pts["E_round_class_sweep"]["sweep"]["25000"].values()]
    b_all = pts["F_excess_count"]["B"]
    b0 = b_all["degree 7, window 2500"]
    dep = pts["G_department_placebos"].values()
    c3 = pts["C_coverage_rule_as_written"]
    rule = pts["B_rule_on_cells_with_no_limit"]
    return {
        "X1": a["D40"][0] > 0 and a["D25"][1] < 0,
        "X2": width(a["S|after|40000|E"]) > width(summary["intervals"]["S|after|40000|E"]),
        "X3": all(c3[n]["D40"] > 0 and c3[n]["D25"] < 0 for n in c3),
        "X4": any(v["declared_placebos"]["label"] == "beyond round-number pricing" for k, v in rule.items() if k.startswith("G|")),
        "X5": makeup["S|after"]["40000"]["share_tier_1000"] < 0.5,
        "X6": tier["cells"]["S|after"]["figures"]["40000"]["E"] >= 2 and cis["no_round_1000"]["D40"][0] > 0 and cis["no_round_1000"]["D25"][1] < 0,
        "X7": tier["placebo_115000"]["S|after"] < 1.2,
        "X8": d["no_round_100"]["D40"] > 0 and d["no_round_100"]["D25"] < 0,
        "X9": max(d25_sweep) < 0,
        "X10": pts["E_round_class_sweep"]["k10_held_at_before"]["E"]["S|after"] > 3,
        "X11": max(abs(v / b0 - 1) for v in b_all.values()) <= 0.15,
        "X12": sum(1 for v in dep if v["E"] > v["highest_placebo"]) >= 9,
    }


def walk(a, b, path, bad):
    if isinstance(a, dict):
        for k in a:
            if k not in b:
                bad.append(f"{path}/{k} missing")
            else:
                walk(a[k], b[k], f"{path}/{k}", bad)
    elif isinstance(a, list):
        if len(a) != len(b):
            bad.append(f"{path}: length")
        else:
            for i, (x, y) in enumerate(zip(a, b)):
                walk(x, y, f"{path}/{i}", bad)
    elif isinstance(a, (int, float)) and not isinstance(a, bool):
        if abs(a - b) > 1e-6 * max(1.0, abs(a)):
            bad.append(f"{path}: {a} vs {b}")
    elif a != b:
        bad.append(f"{path}: differs")


def replay():
    saved = load("results/change-1.json")
    pts = points(load("results/summary.json"), load("results/histograms.json"), saved["counts"])
    bad = []
    walk(pts, saved["points"], "points", bad)
    for b in bad[:20]:
        print(b)
    print(f"VERDICT: {'PASS' if not bad else 'FAIL'} (replay of every Change 1 point estimate from the public results; {len(bad)} differences)")
    return 1 if bad else 0


def main(path):
    with open(path, encoding="utf-8") as f:
        doc = json.load(f)
    summary, hist, decl = load("results/summary.json"), load("results/histograms.json"), load("change-1-public.json")
    frozen_sha = load("data/sources.json")["contracts"]["sha256"]
    if doc["sha256"] != frozen_sha:
        print("VERDICT: FAIL the aggregated cells did not come from the pinned source bytes")
        return 1
    counts = public_counts(doc)
    pts = points(summary, hist, counts)
    makeup, shadows = public_makeup(doc)
    cis, n_orgs = bootstrap(doc, np.random.default_rng(SEED))
    held = score(pts, cis, makeup, summary)
    res = {"note": "Change 1, added after the results were seen. See change-1-public.json. Not part of the frozen protocol, and not in any hit rate.",
           "source_sha256": doc["sha256"], "whole_department_clusters": n_orgs, "replicates": REPS, "seed": SEED,
           "intervals_whole_department": cis, "makeup_of_top_bins": makeup, "counts_at_limit_plus_tax": shadows,
           "predictions": {p["id"]: {"text": p["text"], "held": bool(held[p["id"]])} for p in decl["predictions"]},
           "points": pts, "counts": counts}
    with open(os.path.join(ROOT, "results", "change-1.json"), "w", encoding="utf-8") as f:
        json.dump(res, f, indent=1)
        f.write("\n")
    print(json.dumps({k: bool(v) for k, v in held.items()}))
    print("VERDICT: PASS (Change 1 written)")
    return 0


if __name__ == "__main__":
    sys.exit(replay() if sys.argv[1] == "--replay" else main(sys.argv[1]))
