"""Estimate the fee's effect on trips touching the zone by three methods, and repeat each on 200 placebo dates.

Usage: estimate.py <results dir> <protocol-r1.json>
Reads results/daily.csv and results/donors.parquet (tools/build_series.py); writes results/summary.json and
results/weekly.csv. Every number follows protocol-r1.json.
"""
import csv
import datetime as dt
import json
import sys

import numpy as np
import pyarrow.parquet as pq
from scipy.optimize import nnls

W = 364
D0 = dt.date(2022, 1, 1)


def load(results):
    rows = list(csv.DictReader(open(f"{results}/daily.csv")))
    days = [dt.date.fromisoformat(r["day"]) for r in rows]
    assert days[0] == D0 and all((b - a).days == 1 for a, b in zip(days, days[1:])), "daily series has gaps"
    cols = {k: np.array([float(r[k] or 0) for r in rows]) for k in rows[0] if k != "day"}
    t = pq.read_table(f"{results}/donors.parquet").to_pydict()
    zones = sorted(set(t["pu"]))
    zi = {z: i for i, z in enumerate(zones)}
    don = np.zeros((len(days), len(zones)))
    for d, z, n in zip(t["day"], t["pu"], t["trips"]):
        don[(d - D0).days, zi[z]] = n
    return days, cols, zones, don


def idx(day):
    return (day - D0).days


def windows(t):
    i = idx(t)
    assert i - W >= 0, t
    return slice(i - W, i), slice(i, i + W)


def before_after(T, t):
    pre, post = windows(t)
    return float(np.log(T[post]).mean() - np.log(T[pre]).mean())


def did(T, C, t):
    pre, post = windows(t)
    g = np.log(T) - np.log(C)
    return float(g[post].mean() - g[pre].mean())


def weekly(x, t):
    i = idx(t)
    seg = x[i - W:i + W]
    return seg.reshape(2 * W // 7, 7, *seg.shape[1:]).sum(axis=1)


def synth(T, don, t, min_daily=100):
    pre, _ = windows(t)
    keep = (don[pre].mean(axis=0) >= min_daily)
    wt = weekly(T, t)
    wd = weekly(don[:, keep], t)
    keep2 = (wd > 0).all(axis=0)
    wd = wd[:, keep2]
    nb = W // 7
    y = np.log(wt) - np.log(wt[:nb]).mean()
    X = np.log(wd) - np.log(wd[:nb]).mean(axis=0)
    lam = 1e3
    A = np.vstack([X[:nb], lam * np.ones((1, X.shape[1]))])
    b = np.concatenate([y[:nb], [lam]])
    w, _ = nnls(A, b, maxiter=50 * A.shape[1])
    w = w / w.sum()
    synth_y = X @ w
    gap = y - synth_y
    return {"d": float(gap[nb:].mean()), "pre_rmse": float(np.sqrt((gap[:nb] ** 2).mean())),
            "donors": int(X.shape[1]), "nonzero_weights": int((w > 1e-4).sum()), "weights": w, "y": y, "synth": synth_y,
            "zones_mask": (keep, keep2)}


def pct(d):
    return round(100 * (np.exp(d) - 1), 2)


def placebo_dates(proto):
    p = proto["placebo"]
    start, end = dt.date(2023, 1, 1), dt.date(2024, 1, 4)
    cand = [start + dt.timedelta(days=k) for k in range((end - start).days + 1)]
    rng = np.random.default_rng(p["seed"])
    pick = rng.choice(len(cand), size=p["n"], replace=False)
    return sorted(cand[k] for k in pick)


def readout(real, plac):
    plac = np.asarray(plac)
    return {"estimate_pct": pct(real), "d": real,
            "placebo_at_or_below": int((plac <= real).sum()), "placebo_n": int(len(plac)),
            "placebo_p05_pct": pct(np.percentile(plac, 5)), "placebo_median_pct": pct(np.median(plac)),
            "placebo_p95_pct": pct(np.percentile(plac, 95)),
            "placebo_pct": [pct(x) for x in plac]}


def run(results, proto_path):
    proto = json.load(open(proto_path))
    days, c, zones, don = load(results)
    T, C = c["treated"], c["comparison"]
    launch = dt.date.fromisoformat(proto["launch"])
    pdates = placebo_dates(proto)
    out = {"launch": str(launch), "window_days": W, "placebo_dates": [str(x) for x in pdates]}
    methods = {
        "before_after": lambda t: before_after(T, t),
        "did": lambda t: did(T, C, t),
        "synthetic_control": lambda t: synth(T, don, t)["d"],
        "did_vs_manhattan_rest": lambda t: did(T, c["comparison_manhattan"], t),
        "did_vs_outer": lambda t: did(T, c["comparison_outer"], t),
    }
    out["methods"] = {k: readout(f(launch), [f(t) for t in pdates]) for k, f in methods.items()}
    sc = synth(T, don, launch)
    out["synthetic_control_fit"] = {"pre_rmse_log": round(sc["pre_rmse"], 4), "donors": sc["donors"],
                                    "nonzero_weights": sc["nonzero_weights"]}
    pre, post = windows(launch)
    out["levels"] = {
        "treated_daily_before": round(float(T[pre].mean())), "treated_daily_after": round(float(T[post].mean())),
        "comparison_daily_before": round(float(C[pre].mean())), "comparison_daily_after": round(float(C[post].mean())),
        "comparison_change_pct": pct(float(np.log(C[post]).mean() - np.log(C[pre]).mean())),
        "treated_fee_share_after": round(float(c["treated_fee_trips"][post].sum() / T[post].sum()), 4),
        "excluded_share_before": round(float(c["excluded"][pre].sum() / c["all_trips"][pre].sum()), 4),
    }
    # Reconciliation with the official count (January to September, 2025 against 2024, mean daily trips touching the
    # zone). Added after the design commit and before any result was seen.
    a = slice(idx(dt.date(2025, 1, 1)), idx(dt.date(2025, 10, 1)))
    b = slice(idx(dt.date(2024, 1, 1)), idx(dt.date(2024, 10, 1)))
    out["official_period"] = {
        "treated_jan_sep_change_pct": round(100 * (T[a].mean() / T[b].mean() - 1), 2),
        "comparison_jan_sep_change_pct": round(100 * (C[a].mean() / C[b].mean() - 1), 2),
        "note": "mean daily trips, 2025-01-01 to 2025-09-30 against 2024-01-01 to 2024-09-30",
    }
    i0 = idx(launch) - W
    with open(f"{results}/weekly.csv", "w", newline="") as fh:
        wr = csv.writer(fh)
        wr.writerow(["week_start", "treated", "comparison", "treated_index_log", "synthetic_index_log"])
        wt, wc = weekly(T, launch), weekly(C, launch)
        for k in range(len(wt)):
            wr.writerow([str(D0 + dt.timedelta(days=i0 + 7 * k)), int(wt[k]), int(wc[k]),
                         round(float(sc["y"][k]), 5), round(float(sc["synth"][k]), 5)])
    json.dump(out, open(f"{results}/summary.json", "w"), indent=1)
    return out


if __name__ == "__main__":
    o = run(sys.argv[1], sys.argv[2])
    for k, v in o["methods"].items():
        print(k, v["estimate_pct"], f'{v["placebo_at_or_below"]}/200', v["placebo_p05_pct"], v["placebo_median_pct"], v["placebo_p95_pct"])
    print(json.dumps({k: o[k] for k in ("synthetic_control_fit", "levels", "official_period")}))
