"""Recompute the study's declared estimates from the published cells and compare them with results/results-public.json.

It calls the study's own estimator (code/estimate.py, code/estimators.py) on data/public-cells/, with the same seeds, and
fails on any difference. It needs numpy and scipy, no key, no network and no record-level data. It estimates nothing new.

Replayed: the seven pooled estimates, the event studies and fake break dates for the two main outcomes, and every
robustness row the cells can reach (pandemic quarters included, software and data group dropped, post period ending
before the tariffs, goods-producing groups dropped, 2022 baseline, equal weights, two post windows, trend carried
forward). Not reachable from the cells, because they need the scores, provinces, immigrant status or ages 22 to 24:
the continuous and cutoff forms, the province effects, the other exposure constructions, the non-immigrant and 22 to 24
rows, the industry-mix control, usage against capability and the randomisation inference.

Usage: python3 -B tools/replay.py [--main-only]
--main-only replays only the seven pooled estimates. 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"))
import estimate as E  # noqa: E402

TOL = 1e-6
R = json.loads((ROOT / "results" / "results-public.json").read_text(encoding="utf-8"))
ORDER = ["P1", "S2", "S3", "S4", "S5", "S6", "S7"]
COLS = {("ur", "all"): ("unemployment_rate", "weight_labour_force"),
        ("log_emp", "all"): ("log_employment", "weight_employment"),
        ("hours", "all"): ("usual_weekly_hours", "weight_employment"),
        ("own_share", "all"): ("own_account_share", "weight_employment"),
        ("log_wage", "all"): ("log_hourly_wage", "weight_wage_employees"),
        ("ur", "20_24"): ("unemployment_rate_20_24", "weight_labour_force_20_24"),
        ("recent_share", "20_24"): ("recent_hire_share_20_24", "weight_employment_20_24")}
FILES = {"all": "quarterly.csv", "20_24": "half-yearly.csv"}


def period_index(label):
    y, rest = int(label[:4]), label[4:]
    return (y - 2016) * 4 + int(rest[1]) - 1 if rest[0] == "Q" else (y - 2016) * 2 + int(rest[1]) - 1


class PublicData:
    """Stands in for estimate.Data: the same Y, weights and mid methods, answered from the published cells."""

    def __init__(self):
        self.tables = {name: list(csv.DictReader(open(ROOT / "data" / "public-cells" / name, encoding="utf-8")))
                       for name in FILES.values()}
        arm = {int(r["group"]): r["arm"] for r in self.tables["quarterly.csv"]}
        self.midpoint = np.array([{"High": 0.9, "Low": 0.1}.get(arm.get(g + 1), 0.5) for g in range(43)])

    def mid(self, variant="observed_emp"):
        return self.midpoint

    def Y(self, outcome, ages, period, immig=E.ALL_IMMIG, by_prov=False):
        assert immig == E.ALL_IMMIG and not by_prov
        col, _ = COLS[outcome, ages]
        a = np.full((43, 44 if period == "quarter" else 22), np.nan)
        for r in self.tables[FILES[ages]]:
            if r[col]:
                a[int(r["group"]) - 1, period_index(r["period"])] = float(r[col])
        return a

    def weights(self, outcome, ages, immig=E.ALL_IMMIG, by_prov=False):
        assert immig == E.ALL_IMMIG and not by_prov
        _, col = COLS[outcome, ages]
        w = np.zeros(43)
        for r in self.tables[FILES[ages]]:
            w[int(r["group"]) - 1] = float(r[col])
        return w


problems = []
checked = 0


def close(name, got, want, tol=TOL):
    global checked
    checked += 1
    if got is None or want is None or abs(got - want) > tol:
        problems.append(f"{name}: replay {got} against stored {want}")


def compare(name, got, want):
    close(f"{name} b", got["b"], want["b"])
    close(f"{name} se", got["se_cr1"], want["se_cr1"])
    close(f"{name} wcr p", got["p_wcr"], want["p_wcr"])
    close(f"{name} wcr ci low", got["ci_wcr"][0], want["ci_wcr"][0])
    close(f"{name} wcr ci high", got["ci_wcr"][1], want["ci_wcr"][1])


def main():
    data = PublicData()
    # the headline cell count, from the file a reader downloads
    q = data.tables["quarterly.csv"]
    assert len(q) == 860 and len({r["group"] for r in q}) == 20, "unexpected cells"
    for i, oid in enumerate(ORDER):
        got = E.pooled(data, oid, E.SEED + i)
        compare(oid, got, R["outcomes"][oid])
        print(f"{oid}: b {got['b']:.6f}, wcr p {got['p_wcr']:.4f}")
    if "--main-only" not in sys.argv:
        rob = {r["id"]: r for r in R["robustness"]}
        for oid, offset in (("P1", 0), ("S3", 2)):
            K = E.KIND[E.OUTCOMES[oid][2]]
            ev = E.event_study(data, oid, E.SEED + 50 + offset)
            stored = R["event_studies"][oid]
            for a, b in zip(ev["coefs"], stored["coefs"]):
                assert a["period"] == b["period"]
                close(f"event {oid} {a['period']}", a["b"], b["b"])
            close(f"event {oid} cr1 wald", ev["pretrend_wald_cr1"]["F"], stored["pretrend_wald_cr1"]["F"])
            close(f"event {oid} wcr wald", ev["pretrend_wald_wcr_p"], stored["pretrend_wald_wcr_p"])
            for a, b in zip(E.placebo(data, oid)["placebos"], R["placebos"][oid]["placebos"]):
                assert a["break"] == b["break"]
                close(f"fake date {oid} {a['break']}", a["b"], b["b"])
                close(f"fake date {oid} {a['break']} p", a["p_cr1"], b["p_cr1"])
            rows = {
                "R3": lambda: E.pooled(data, oid, E.SEED + 220, periods=K["pre"][:len(K["y1619"])] + K["covid"] + K["ref"] + K["post"]),
                "R8": lambda: E.pooled(data, oid, E.SEED + 240, *E.arms(data, drop_high=(11,))),
                "R9": lambda: E.pooled(data, oid, E.SEED + 250, periods=K["pre"] + K["early"], posts=[K["early"]]),
                "R13": lambda: E.pooled(data, oid, E.SEED + 260, periods=K["ref"] + K["post"]),
                "R17": lambda: E.trend_two_step(data, oid, E.SEED + 280),
            }
            for rid, fn in rows.items():
                compare(f"{rid}_{oid}", fn(), rob[f"{rid}_{oid}"])
            two = E.pooled(data, oid, E.SEED + 270, posts=[K["early"], K["late"]])
            compare(f"R16_{oid}", two["coefs"][0], rob[f"R16_{oid}"])
            compare(f"R16_{oid}#1", two["coefs"][1], rob[f"R16_{oid}#1"])
            print(f"{oid}: event study, fake dates and robustness rows replayed")
        compare("R10_P1", E.pooled(data, "P1", E.SEED + 300, *E.arms(data, drop_low=(40, 41, 42, 43))), rob["R10_P1"])
        compare("R15_P1", E.pooled(data, "P1", E.SEED + 340, equal_w=True), rob["R15_P1"])
    for p in problems:
        print(p)
    print(f"VERDICT: {'PASS' if not problems else 'FAIL'} ({checked} values compared, {len(problems)} differ)")
    return 1 if problems else 0


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