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

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

Usage: python3 -B tools/additions2.py [--only B1,B5.0] [--compare]
--only runs the named sections and merges them into the file. B5 and B6 run one seed per section: B5.0, B5.1, B5.2, B6.0, B6.1,
B6.2. --compare recomputes and reports differences, writing nothing. The last line printed is the verdict.
"""
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 additions as A  # noqa: E402
import estimate as E  # noqa: E402
import estimators as est  # noqa: E402
from replay import PublicData  # noqa: E402

OUT = ROOT / "results" / "additions-2.json"
FIRST = json.loads((ROOT / "results" / "additions.json").read_text(encoding="utf-8"))
S0 = E.SEED + 2000
TRADES = (A.TECHNICAL_TRADES, A.GENERAL_TRADES)
BUSINESS = 6
HIGH_PAIR = (A.SOFTWARE_AND_DATA, BUSINESS)
K_Q = A.K_Q
FROM_2018 = list(range(8, 16)) + K_Q["ref"] + K_Q["post"]
BASELINE_2022 = K_Q["ref"] + K_Q["post"]
PANELS, WALD_DRAWS, COVERAGE_DRAWS, SEEDS = 500, 499, 999, 3
PLANT = 1.5
args = sys.argv[1:]
ALL = ["B0", "B1", "B2", "B3", "B4"] + [f"B5.{i}" for i in range(SEEDS)] + [f"B6.{i}" for i in range(SEEDS)]
ONLY = args[args.index("--only") + 1].split(",") if "--only" in args else ALL
COMPARE = "--compare" in args


def b0_windows(data):
    pg = FIRST["per_group"]
    high, low = [r for r in pg["groups"] if r["arm"] == "High"], [r for r in pg["groups"] if r["arm"] == "Low"]
    rest = [r for r in low if r["group"] not in TRADES]

    def mean(rows, year):
        return sum(r["weight"] * r["annual"][year] for r in rows) / sum(r["weight"] for r in rows)

    out = []
    for end in ("2017", "2018", "2019", "2022"):
        h = mean(high, "2016") - mean(high, end)
        with_trades = mean(low, "2016") - mean(low, end) - h
        without = mean(rest, "2016") - mean(rest, end) - h
        out.append({"from": "2016", "to": end, "gap_move_with_trades": with_trades, "gap_move_without_trades": without,
                    "share_removed": 1 - without / with_trades})
    return out


def settings(data, seed, high, low, declared=True):
    out = {}
    if declared:
        out["declared"] = A.row(E.pooled(data, "P1", seed, high, low))
    out["baseline_2022"] = A.row(E.pooled(data, "P1", seed + 10, high, low, periods=BASELINE_2022))
    out["from_2018"] = A.row(E.pooled(data, "P1", seed + 20, high, low, periods=FROM_2018))
    out["trend_both_steps"] = A.two_step(data, "P1", seed + 30, high, low)
    out["fake_dates"] = A.fake_dates(data, "P1", seed + 40, high, low)
    return out


def b1_without_trades(data):
    return settings(data, S0 + 100, *E.arms(data, drop_low=TRADES), declared=False)


def b2_mirror(data):
    return settings(data, S0 + 200, *E.arms(data, drop_high=HIGH_PAIR))


def b3_both_pairs(data):
    return A.row(E.pooled(data, "P1", S0 + 300, *E.arms(data, drop_high=HIGH_PAIR, drop_low=TRADES)))


def b4_each_group(data):
    out = []
    for r in FIRST["per_group"]["groups"]:
        g = r["group"]
        drop = {"drop_high": (g,)} if r["arm"] == "High" else {"drop_low": (g,)}
        row = A.row(E.pooled(data, "P1", S0 + 400 + g, *E.arms(data, **drop)))
        out.append({"group": g, "arm": r["arm"], **row})
        print(f"  group {g} done", flush=True)
    return out


def b5_pretrend(data, seed_i):
    high, low = E.arms(data)
    groups = np.array(sorted(high + low))
    periods = K_Q["pre"] + K_Q["post"]
    o = E.build_obs(data.Y("ur", "all", "quarter"), data.weights("ur", "all"), list(groups), periods, K_Q["py"])
    g, t, w = o["g"], o["t"], o["w"]
    fe = E.make_fe(o)
    ks = [k for k in periods if k not in K_Q["ref"]]
    masks = np.column_stack([t == k for k in ks]).astype(float)
    pre = [j for j, k in enumerate(ks) if k in K_Q["y1619"]]
    Rm = np.zeros((len(pre), len(ks)))
    for r, j in enumerate(pre):
        Rm[r, j] = 1.0
    hi_real = np.isin(g, high).astype(float)
    real = est.Fit(o["y"], masks * hi_real[:, None], w, g, fe)
    _, cl = np.unique(g, return_inverse=True)

    def rates(form, plant, seed):
        gap = np.where(t < 24, -plant * (24 - t) / 24, 0.0)
        rej_cr1 = rej_boot = 0
        for r in range(PANELS):
            rng = np.random.default_rng(seed + r)
            if form == "sign_flipped_residuals":
                hi = hi_real
                y = rng.choice([-1.0, 1.0], size=len(groups))[cl] * real.e + hi * gap
            else:
                hi = np.isin(g, rng.choice(groups, size=len(high), replace=False)).astype(float)
                y = o["y"] + hi * gap
            fit = est.Fit(y, masks * hi[:, None], w, g, fe)
            rej_cr1 += fit.wald_cr1(Rm)[1] < 0.05
            rej_boot += est.wald_wcr(fit, Rm, est.draws(fit.G, WALD_DRAWS, seed + 100000 + r))[1] < 0.05
        return {"form": form, "planted_points": plant, "panels": PANELS, "cr1_reject_rate": rej_cr1 / PANELS, "bootstrap_reject_rate": rej_boot / PANELS}

    out = []
    for i, form in enumerate(("sign_flipped_residuals", "arms_reassigned")):
        for j, plant in enumerate((0.0, PLANT)):
            out.append(rates(form, plant, S0 + 1000000 * (1 + seed_i) + 200000 * i + 300000 * j))
            print(f"  {form} planted {plant}: done", flush=True)
    return out


class Synthetic(PublicData):
    """Real shape and weights, with one outcome's series replaced."""

    def __init__(self, base, key, series):
        self.tables, self.midpoint = base.tables, base.midpoint
        self.key, self.series = key, series

    def Y(self, outcome, ages, period, immig=E.ALL_IMMIG, by_prov=False):
        assert (outcome, ages) == self.key
        return self.series


def b6_coverage(data, seed_i):
    out = []
    for n, oid in enumerate(("P1", "S3")):
        outcome, ages, _ = E.OUTCOMES[oid]
        real = A.two_step(data, oid, 0, parts_only=True)
        g, t = real["g"], real["t"]
        levels, cl = np.unique(g, return_inverse=True)
        hi = np.isin(g, real["high"]).astype(float)
        cov_both = cov_fixed = 0
        seed = S0 + 5000000 * (1 + seed_i) + 500000 * n
        for r in range(PANELS):
            rng = np.random.default_rng(seed + r)
            y = real["slope"] * hi * t + rng.choice([-1.0, 1.0], size=len(levels))[cl] * real["residual"]  # a true effect of zero
            series = np.full(real["shape"], np.nan)
            series[g, t] = y
            res = A.two_step(Synthetic(data, (outcome, ages), series), oid, seed + 100000 + r, n_draws=COVERAGE_DRAWS, test_at=0.0)
            cov_both += res["p_both_steps"] >= 0.05
            cov_fixed += res["p_slope_held_fixed"] >= 0.05
        out.append({"outcome": oid, "panels": PANELS, "covered_both_steps": cov_both / PANELS, "covered_slope_held_fixed": cov_fixed / PANELS})
        print(f"  {oid}: done", flush=True)
    return out


SECTIONS = {"B0": ("windows_with_and_without_trades", b0_windows), "B1": ("without_trades", b1_without_trades), "B2": ("mirror_without_software_and_business", b2_mirror),
            "B3": ("both_pairs_out", b3_both_pairs), "B4": ("each_group_left_out", b4_each_group)}


def run(sec, data):
    if sec.startswith("B5."):
        return ("pretrend_tests_on_own_noise", sec.split(".")[1]), b5_pretrend(data, int(sec.split(".")[1]))
    if sec.startswith("B6."):
        return ("trend_interval_coverage", sec.split(".")[1]), b6_coverage(data, int(sec.split(".")[1]))
    key, fn = SECTIONS[sec]
    return (key, None), fn(data)


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-2.md, and built after a second critical read of the page. 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. Sections with a number per key are one seed each.")}
    problems = []
    for sec in ONLY:
        (key, sub), res = run(sec, data)
        if COMPARE:
            A.same(res, stored[key][sub] if sub else stored[key], key, problems)
        else:
            if sub:
                stored.setdefault(key, {})[sub] = res
            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())
