"""Every declared estimate (DESIGN.md, plan/protocol.json, plan/amendment-1.json) from the prescriber table.

Reads PE_WORK/prescribers.csv (prescriber-level, never committed) and writes results/estimates.json, which holds
aggregates over at least 11 prescribers only.

    python -B -m pe.analyze
"""
from __future__ import annotations

import json
import os
from pathlib import Path

import numpy as np
import pandas as pd

from pe import estimators as E

HERE = Path(__file__).resolve().parent.parent
PROTOCOL = json.loads((HERE / "plan" / "protocol.json").read_text(encoding="utf-8"))
FAMS = ["A", "B"]
OTHER = {"A": "B", "B": "A"}


def load() -> pd.DataFrame:
    t = pd.read_csv(Path(os.environ["PE_WORK"]) / "prescribers.csv", dtype={"npi": str})
    if len(t) < 1000:
        raise SystemExit("prescriber table looks empty")
    return t


def specialty_groups(raw: pd.Series) -> pd.Series:
    counts = raw.value_counts()
    keep = set(counts[counts >= PROTOCOL["specialty_min_prescribers"]].index)
    return raw.where(raw.isin(keep), "Other")


def design_matrix(t: pd.DataFrame, f: str, treat: np.ndarray) -> np.ndarray:
    cols = [np.ones(len(t)), treat.astype(float), t[f"share{f}_2022"].to_numpy(float),
            np.log(t["cls_2022"].to_numpy(float))]
    X = np.column_stack(cols)
    return np.column_stack([X, E.dummies(t["spec"].to_numpy()), E.dummies(t["division"].to_numpy())])


def regression(t: pd.DataFrame, f: str) -> dict:
    treat = t[f"eng{f}_2023"].to_numpy() == 1
    beta, se = E.ols_hc1(t[f"share{f}_2023"].to_numpy(float), design_matrix(t, f, treat))
    return {"estimate": float(beta[1]), "interval": [float(beta[1] - 1.96 * se[1]), float(beta[1] + 1.96 * se[1])],
            "prior_share_coef": float(beta[2])}


def run() -> dict:
    t = load()
    t["spec"] = specialty_groups(t["specialty_raw"])
    vol22 = E.fifths(t["cls_2022"].to_numpy())
    vol21 = E.fifths(t["cls_2021"].to_numpy())
    spec = t["spec"].to_numpy()
    div = t["division"].to_numpy()
    N = len(t)
    boot = PROTOCOL["bootstrap"]
    out: dict = {"population": E.cell(N, N), "drugs": {}}
    out["specialties"] = sorted(set(spec))
    min50 = np.ones(N, dtype=bool)
    for y in ["2021", "2022", "2023"]:
        min50 &= t[f"cls_{y}"].to_numpy() >= 50
    out["population_min50"] = E.cell(int(min50.sum()), int(min50.sum()))

    plans = {}
    for f in FAMS:
        e22 = t[f"eng{f}_2022"].to_numpy() == 1
        e23 = t[f"eng{f}_2023"].to_numpy() == 1
        new = e23 & ~e22
        never = ~e23 & ~e22
        s = {y: t[f"share{f}_{y}"].to_numpy(float) for y in ["2021", "2022", "2023"]}
        so = {y: t[f"share{OTHER[f]}_{y}"].to_numpy(float) for y in ["2021", "2022", "2023"]}
        st22 = E.strata_codes(spec, div, vol22, E.share_band(s["2022"]))
        st21 = E.strata_codes(spec, div, vol21, E.share_band(s["2021"]))
        npay = t[f"pay{f}_n_2023"].to_numpy(float)
        did_mask = new | never
        dose = {"1": new & (npay == 1), "2-4": new & (npay >= 2) & (npay <= 4), "5+": new & (npay >= 5)}
        plans[f] = dict(e22=e22, e23=e23, new=new, never=never, s=s, so=so, st22=st22, st21=st21,
                        did_mask=did_mask, dose=dose)

    def estimates(f: str, w: np.ndarray) -> dict:
        p = plans[f]
        m = p["did_mask"]
        r = {"raw": E.raw_diff(p["s"]["2023"], p["e23"], w),
             "matched": E.cem_att(p["s"]["2023"], p["e23"], p["st22"], w)["att"],
             "new_engagement": E.cem_att((p["s"]["2023"] - p["s"]["2022"])[m], p["new"][m], p["st22"][m], w[m])["att"],
             "placebo": E.cem_att((p["s"]["2022"] - p["s"]["2021"])[m], p["new"][m], p["st22"][m], w[m])["att"],
             "placebo_2021_match": E.cem_att((p["s"]["2022"] - p["s"]["2021"])[m], p["new"][m], p["st21"][m], w[m])["att"],
             "other_drug": E.cem_att((p["so"]["2023"] - p["so"]["2022"])[m], p["new"][m], p["st22"][m], w[m])["att"]}
        r["trend_adjusted"] = r["new_engagement"] - r["placebo"]
        r["trend_adjusted_2021_match"] = r["new_engagement"] - r["placebo_2021_match"]
        for band, dm in p["dose"].items():
            mm = dm | p["never"]
            r[f"dose_{band}"] = E.cem_att((p["s"]["2023"] - p["s"]["2022"])[mm], dm[mm], p["st22"][mm], w[mm])["att"]
        mm = min50
        r["matched_min50"] = E.cem_att(p["s"]["2023"][mm], p["e23"][mm], p["st22"][mm], w[mm])["att"]
        return r

    ones = np.ones(N)
    point = {f: estimates(f, ones) for f in FAMS}
    rng = np.random.default_rng(boot["seed"])
    draws = {f: {k: [] for k in point[f]} for f in FAMS}
    for _ in range(boot["draws"]):
        w = E.boot_counts(rng, N)
        for f in FAMS:
            for k, v in estimates(f, w).items():
                draws[f][k].append(v)
    rng_c = np.random.default_rng(boot["seed"] + 1)
    state = t["state"].to_numpy()
    cdraws = {f: [] for f in FAMS}
    for _ in range(boot["draws"]):
        w = E.cluster_boot_counts(rng_c, state)
        for f in FAMS:
            p = plans[f]
            m = p["did_mask"]
            cdraws[f].append(E.cem_att((p["s"]["2023"] - p["s"]["2022"])[m], p["new"][m], p["st22"][m], w[m])["att"])

    for f in FAMS:
        p = plans[f]
        d: dict = {}
        for k, v in point[f].items():
            d[k] = {"estimate": v, "interval": E.pct_interval(np.array(draws[f][k]))}
        d["new_engagement"]["interval_state_clusters"] = E.pct_interval(np.array(cdraws[f]))
        d["regression"] = regression(t, f)
        mm = min50
        beta, se = E.ols_hc1(t[f"share{f}_2023"].to_numpy(float)[mm],
                             design_matrix(t[mm], f, p["e23"][mm]))
        d["regression_min50"] = {"estimate": float(beta[1]),
                                 "interval": [float(beta[1] - 1.96 * se[1]), float(beta[1] + 1.96 * se[1])]}
        m = p["did_mask"]
        info = E.cem_att((p["s"]["2023"] - p["s"]["2022"])[m], p["new"][m], p["st22"][m])
        d["new_engagement"]["treated_kept"] = int(info["treated_kept"])
        d["new_engagement"]["treated_dropped"] = int(info["treated_dropped"])
        xs = E.cem_att(p["s"]["2023"], p["e23"], p["st22"])
        d["matched"]["treated_kept"] = int(xs["treated_kept"])
        d["matched"]["treated_dropped"] = int(xs["treated_dropped"])
        # matched gap by year (levels), for the chart
        d["matched_gap_by_year"] = {y: E.cem_att(p["s"][y][m], p["new"][m], p["st22"][m])["att"]
                                    for y in ["2021", "2022", "2023"]}
        groups = {"newly_engaged": p["new"], "never_engaged": p["never"], "kept_engaged": p["e22"] & p["e23"],
                  "dropped": p["e22"] & ~p["e23"], "engaged_2023": p["e23"], "not_engaged_2023": ~p["e23"]}
        d["groups"] = {}
        for g, gm in groups.items():
            n = int(gm.sum())
            d["groups"][g] = E.cell(n, {y: float(p["s"][y][gm].mean()) for y in ["2021", "2022", "2023"]})
        dose_n = {b: int(dm.sum()) for b, dm in p["dose"].items()}
        for b in dose_n:
            d[f"dose_{b}"]["n"] = E.cell(dose_n[b], dose_n[b])["n"]
        eng = p["e23"]
        food = t[f"pay{f}_food_2023"].to_numpy(float)[eng].sum()
        rows = t[f"pay{f}_rows_2023"].to_numpy(float)[eng].sum()
        d["payments_2023"] = {
            "engaged_prescribers": E.cell(int(eng.sum()), int(eng.sum())),
            "share_engaged_pct": 100.0 * eng.mean(),
            "median_payments_per_engaged": float(np.median(t[f"pay{f}_n_2023"].to_numpy(float)[eng])),
            "median_amount_per_engaged_usd": float(np.median(t[f"pay{f}_amt_2023"].to_numpy(float)[eng])),
            "food_share_of_records_pct": 100.0 * food / rows,
        }
        d["payments_2023_new"] = {
            "median_payments": float(np.median(t[f"pay{f}_n_2023"].to_numpy(float)[p["new"]])),
            "median_amount_usd": float(np.median(t[f"pay{f}_amt_2023"].to_numpy(float)[p["new"]])),
        }
        d["never_change_sd"] = float(np.std(p["s"]["2023"][p["never"]] - p["s"]["2022"][p["never"]], ddof=1))
        out["drugs"][f] = d
    return out


def main() -> int:
    res = run()
    path = HERE / "results" / "estimates.json"
    path.parent.mkdir(exist_ok=True)
    tmp = path.with_suffix(".tmp")
    tmp.write_text(json.dumps(res, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    tmp.replace(path)
    print(f"wrote {path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
