"""Run the additions declared in additions/DECLARATION.md and write results/additions.json. All added after the results.

From data/public-cells/ with the study's own estimator, so it needs numpy and scipy, no key, no network and no
record-level data. The frozen results are read, never written.

Usage: python3 -B tools/additions.py [--only A2,A5] [--compare]
--only runs the named sections and merges them into the file. --compare recomputes and reports differences, writing nothing.
The last line printed is the verdict.
"""
import csv
import json
import sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "code"))
sys.path.insert(0, str(ROOT / "tools"))
import estimate as E  # noqa: E402
import estimators as est  # noqa: E402
from replay import PublicData  # noqa: E402

OUT = ROOT / "results" / "additions.json"
FROZEN = json.loads((ROOT / "results" / "results-public.json").read_text(encoding="utf-8"))
ROB = {r["id"]: r for r in FROZEN["robustness"]}
S0 = E.SEED + 1000
TECHNICAL_TRADES, GENERAL_TRADES, SOFTWARE_AND_DATA = 35, 36, 11
args = sys.argv[1:]
ONLY = args[args.index("--only") + 1].split(",") if "--only" in args else ["A1", "A2", "A3", "A4", "A5", "A6"]
COMPARE = "--compare" in args
K_Q = E.KIND["quarter"]


def row(r):
    return {k: r[k] for k in ("b", "se_cr1", "p_cr1", "p_wcr", "ci_wcr", "n_obs", "G", "n_high", "n_low") if k in r}


class LogRate(PublicData):
    """The same data with the all-ages unemployment rate on the log scale."""

    def Y(self, outcome, ages, period, immig=E.ALL_IMMIG, by_prov=False):
        a = super().Y(outcome, ages, period, immig, by_prov)
        assert outcome == "ur" and ages == "all"
        with np.errstate(divide="ignore"):
            return np.log(a)


def a1_per_group(data):
    rows = list(csv.DictReader(open(ROOT / "data" / "public-cells" / "quarterly.csv", encoding="utf-8")))
    groups = sorted({int(r["group"]) for r in rows})
    Y = data.Y("ur", "all", "quarter")
    W = data.weights("ur", "all")
    meta = {int(r["group"]): (r["group_label"], r["arm"]) for r in rows}
    years = {"2016": range(0, 4), "2017": range(4, 8), "2018": range(8, 12), "2019": range(12, 16), "2022": range(24, 28),
             "2023": range(28, 32), "2024": range(32, 36), "2025": range(36, 40), "2026": range(40, 43)}
    out = []
    periods = K_Q["pre"] + K_Q["post"]
    for g in groups:
        y = np.array([Y[g - 1, t] for t in periods])
        X = np.zeros((len(periods), 5))
        for i, t in enumerate(periods):
            X[i, t % 4] = 1.0
            X[i, 4] = float(t in K_Q["post"])
        out.append({"group": g, "label": meta[g][0], "arm": meta[g][1], "weight": float(W[g - 1]),
                    "change": float(np.linalg.lstsq(X, y, rcond=None)[0][4]),
                    "annual": {yr: float(np.mean([Y[g - 1, t] for t in ts])) for yr, ts in years.items()}})
    arm = {}
    for name in ("High", "Low"):
        sub = [r for r in out if r["arm"] == name]
        tot = sum(r["weight"] for r in sub)
        arm[name] = {"change": sum(r["weight"] * r["change"] for r in sub) / tot,
                     "annual": {yr: sum(r["weight"] * r["annual"][yr] for r in sub) / tot for yr in years},
                     "weight": tot}
    trades = [r for r in out if r["group"] in (TECHNICAL_TRADES, GENERAL_TRADES)]
    low_w = arm["Low"]["weight"]
    t_change = sum(r["weight"] * r["change"] for r in trades) / low_w
    t_fall = sum(r["weight"] * (r["annual"]["2016"] - r["annual"]["2022"]) for r in trades) / low_w
    return {"groups": out, "arms": arm, "difference_of_arm_changes": arm["High"]["change"] - arm["Low"]["change"],
            "trades_share_of_low_arm_change": t_change / arm["Low"]["change"],
            "trades_share_of_low_arm_fall_2016_to_2022": t_fall / (arm["Low"]["annual"]["2016"] - arm["Low"]["annual"]["2022"]),
            "trades_weight_share_of_low_arm": sum(r["weight"] for r in trades) / low_w}


def a2_leave_out(data):
    return {"without_technical_trades": row(E.pooled(data, "P1", S0 + 10, *E.arms(data, drop_low=(TECHNICAL_TRADES,)))),
            "without_general_trades": row(E.pooled(data, "P1", S0 + 20, *E.arms(data, drop_low=(GENERAL_TRADES,)))),
            "without_both": row(E.pooled(data, "P1", S0 + 30, *E.arms(data, drop_low=(TECHNICAL_TRADES, GENERAL_TRADES))))}


def a3_later_start(data):
    return row(E.pooled(data, "P1", S0 + 40, periods=list(range(8, 16)) + K_Q["ref"] + K_Q["post"]))


def fake_dates(data, oid, seed, high=None, low=None):
    """high and low name other arms for the rows in additions/DECLARATION-2.md; the frozen figures then do not apply."""
    outcome, ages, period = E.OUTCOMES[oid]
    K = E.KIND[period]
    own_arms = high is not None
    if not own_arms:
        high, low = E.arms(data)
    Y, wg = data.Y(outcome, ages, period), data.weights(outcome, ages)
    o = E.build_obs(Y, wg, sorted(high + low), K["y1619"], K["py"])
    hi = np.isin(o["g"], high).astype(float)
    frozen = E.placebo(data, oid)["placebos"]
    out = []
    for i, f in enumerate(frozen):
        k = K["py"] + i
        fit = est.Fit(o["y"], hi * (o["t"] >= k), o["w"], o["g"], E.make_fe(o))
        p = est.wcr_pvalue(fit, [1.0], 0.0, est.draws(fit.G, E.B, seed + i))
        if own_arms:
            out.append({"break": f["break"], "b": float(fit.b[0]), "p_wcr": float(p)})
            continue
        assert abs(fit.b[0] - f["b"]) < 1e-9
        out.append({"break": f["break"], "b": f["b"], "p_cr1": f["p_cr1"], "p_wcr": float(p)})
    return out


def a4_fake_dates(data):
    out = {"P1": fake_dates(data, "P1", S0 + 100), "S3": fake_dates(data, "S3", S0 + 200)}
    for oid in out:  # the frozen conventional figures must come back unchanged
        for a, b in zip(out[oid], FROZEN["placebos"][oid]["placebos"]):
            assert a["break"] == b["break"] and abs(a["b"] - b["b"]) < 1e-6 and abs(a["p_cr1"] - b["p_cr1"]) < 1e-6
    return out


def two_step(data, oid, seed, high=None, low=None, n_draws=None, test_at=None, parts_only=False):
    """The earlier-trend row with both steps re-estimated in every draw. See the method line in the declaration.
    high and low name other arms, and test_at returns the p-value at one value with the slope re-estimated and with it
    held fixed, for the rows and the coverage check in additions/DECLARATION-2.md."""
    outcome, ages, period = E.OUTCOMES[oid]
    K = E.KIND[period]
    own_arms = high is not None or test_at is not None or parts_only
    if high is None:
        high, low = E.arms(data)
    groups = sorted(high + low)
    Y, wg = data.Y(outcome, ages, period), data.weights(outcome, ages)
    o = E.build_obs(Y, wg, groups, K["pre"] + K["post"], K["py"])
    o1 = E.build_obs(Y, wg, groups, K["pre"], K["py"])
    hi = np.isin(o["g"], high).astype(float)
    ht, dpost = hi * o["t"], hi * np.isin(o["t"], K["post"])
    fe = E.make_fe(o)
    w = o["w"]
    # weights of the first step (the slope, pre periods only) and of the later step (the estimate)
    x1 = E.make_fe(o1).demean(np.isin(o1["g"], high) * o1["t"].astype(float))
    a1 = o1["w"] * x1 / np.sum(o1["w"] * x1 ** 2)
    pre = np.isin(o["t"], K["pre"])
    assert np.array_equal(o["g"][pre], o1["g"]) and np.array_equal(o["t"][pre], o1["t"])
    a = np.zeros(len(w))
    a[pre] = a1
    Dt = fe.demean(dpost)
    d = w * Dt / np.sum(w * Dt ** 2)
    kappa = float(d @ ht)
    c = d - kappa * a
    yt, Ht = fe.demean(o["y"]), fe.demean(ht)
    tau, b = float(a @ o["y"]), float(c @ o["y"])
    frozen = ROB[f"R17_{oid}"]
    if not own_arms:
        assert abs(b - frozen["b"]) < 1e-7, (b, frozen["b"])
        assert abs(tau - frozen["pre_trend_slope_per_period"]) < 1e-7
    assert abs(c @ ht) < 1e-7 and abs(c @ dpost - 1.0) < 1e-7
    cl_levels, cl = np.unique(o["g"], return_inverse=True)
    G = len(cl_levels)
    n = len(w)

    def se_of(weights, e, k):
        z = np.zeros(G)
        np.add.at(z, cl, weights * e)
        cc = G / (G - 1) * (n - 1) / (n - (k + fe.k_not_nested))
        return float(np.sqrt(cc * np.sum(z ** 2)))

    e_hat = yt - tau * Ht - b * Dt
    if parts_only:
        return {"g": o["g"], "t": o["t"], "residual": e_hat, "slope": tau, "b": b, "high": high, "shape": Y.shape, "weights": wg}
    se = se_of(c, e_hat, 2)
    se_known = se_of(d, e_hat, 1)  # positive control: with the slope held fixed this must be the frozen standard error
    if not own_arms:
        assert abs(se_known - frozen["se_cr1"]) < 1e-6, (se_known, frozen["se_cr1"])
    cc = G / (G - 1) * (n - 1) / (n - (2 + fe.k_not_nested))
    V_all = est.draws(G, n_draws or E.B, seed)

    def pval(b0):
        e0 = yt - tau * Ht - b0 * Dt
        fitted = tau * Ht + b0 * Dt
        t_obs = (b - b0) / se
        exceed = 0
        for s in range(0, V_all.shape[0], 1000):
            V = V_all[s:s + 1000]
            Ys = fitted[:, None] + fe.demean(e0[:, None] * V.T[cl])
            tau_s, b_s = a @ Ys, c @ Ys
            Es = Ys - Ht[:, None] * tau_s - Dt[:, None] * b_s
            Z = np.zeros((G, V.shape[0]))
            np.add.at(Z, cl, c[:, None] * Es)
            t = (b_s - b0) / np.sqrt(cc * (Z ** 2).sum(axis=0))
            exceed += int((np.abs(t) >= abs(t_obs) - 1e-12).sum())
        return exceed / V_all.shape[0]

    if test_at is not None:
        held_fixed = est.Fit(o["y"] - tau * ht, dpost, w, o["g"], fe)
        return {"b": b, "p_both_steps": pval(test_at), "p_slope_held_fixed": float(est.wcr_pvalue(held_fixed, [1.0], test_at, V_all))}
    ci = []
    for direction in (-1, 1):
        inner, outer = b, b + direction * 4 * se
        tries = 0
        while pval(outer) > 0.05 and tries < 6:
            inner, outer = outer, outer + direction * 4 * se
            tries += 1
        for _ in range(16):
            mid = 0.5 * (inner + outer)
            if pval(mid) > 0.05:
                inner = mid
            else:
                outer = mid
        ci.append(0.5 * (inner + outer))
    res = {"b": b, "slope_per_period": tau, "se_both_steps": se, "se_slope_held_fixed": se_known, "p_both_steps": pval(0.0), "ci_both_steps": ci}
    if not own_arms:
        res.update(frozen_p_wcr=frozen["p_wcr"], frozen_ci_wcr=frozen["ci_wcr"])
    return res


def a5_two_step(data):
    return {"P1": two_step(data, "P1", S0 + 300), "S3": two_step(data, "S3", S0 + 400)}


def a6_log_rate(data):
    ld = LogRate()
    Y = ld.Y("ur", "all", "quarter")
    high, low = E.arms(ld)
    cells = [(g, t) for g in high + low for t in K_Q["pre"] + K_Q["post"]]
    dropped = sum(1 for g, t in cells if not np.isfinite(Y[g, t]))
    return {"cells_dropped_for_a_zero_rate": dropped,
            "main": row(E.pooled(ld, "P1", S0 + 500)),
            "baseline_2022": row(E.pooled(ld, "P1", S0 + 510, periods=K_Q["ref"] + K_Q["post"])),
            "without_software_and_data": row(E.pooled(ld, "P1", S0 + 520, *E.arms(ld, drop_high=(SOFTWARE_AND_DATA,)))),
            "fake_dates": fake_dates(ld, "P1", S0 + 600)}


SECTIONS = {"A1": ("per_group", a1_per_group), "A2": ("leave_out_trades", a2_leave_out), "A3": ("later_start_2018", a3_later_start),
            "A4": ("fake_dates_bootstrap", a4_fake_dates), "A5": ("two_step_both_steps", a5_two_step), "A6": ("log_rate", a6_log_rate)}


def same(x, y, path, out, tol=1e-9):
    if isinstance(x, dict):
        for k in x:
            same(x[k], y[k], f"{path}.{k}", out, tol)
    elif isinstance(x, list):
        for i, (p, q) in enumerate(zip(x, y)):
            same(p, q, f"{path}[{i}]", out, tol)
    elif isinstance(x, float) and abs(x - y) > tol:
        out.append(f"{path}: {x} against stored {y}")


def main():
    data = PublicData()
    stored = json.loads(OUT.read_text(encoding="utf-8")) if OUT.exists() else {
        "about": ("Added after the results, as declared in additions/DECLARATION.md, and built after a critical read of the first "
                  "draft. Not part of the frozen results and not tests the plan declared. Effects are High minus Low; wcr is the "
                  "wild cluster bootstrap with the null imposed; cr1 the cluster-robust standard error.")}
    problems = []
    for sec in ONLY:
        key, fn = SECTIONS[sec]
        res = fn(data)
        if COMPARE:
            same(res, stored[key], key, problems)
        else:
            stored[key] = res
            OUT.write_text(json.dumps(stored, indent=1) + "\n", encoding="utf-8")
        print(f"{sec} {key}: done", flush=True)
    for p in problems:
        print(p)
    print(f"VERDICT: {'PASS' if not problems else 'FAIL'} ({len(ONLY)} sections, {len(problems)} differences)")
    return 1 if problems else 0


if __name__ == "__main__":
    sys.exit(main())
