"""Change 1 to the protocol, made after the results were seen: exploratory diagnostics of the placebo dates.

Nothing here changes a scored result. results/summary.json and tools/estimate.py stay as committed; this file reuses
estimate.py's functions unchanged and writes results/change1-diagnostics.json:
  - per method: the launch's log difference d, the placebo log differences, the historical adjustment exp(d - median)
    - 1 on the declared log scale, the same against only the latest 50 placebo dates (anchors in late 2023), and the
    drift of placebo estimates across anchor dates (a least-squares slope, percentage points per year of anchor date);
  - the span of data the placebo windows cover;
  - the share of comparison and left-out trips that paid the zone fee in the year after the launch (needs the
    aggregate files; skipped, and left empty, when they are absent).
The historical adjustment assumes the drift of the placebo years would have continued unchanged in the fee's year;
the design cannot check that, so it is a diagnostic, not an estimate of the fee's effect.

Usage: diagnostics.py <results dir> <protocol-r1.json> [<aggregates dir> <zones.json> <taxi_zone_lookup.csv>]
"""
import datetime as dt
import json
import math
import os
import statistics
import sys

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import estimate as est  # noqa: E402

LATEST = 50


def run(results, proto_path, agg=None, zones=None, lookup=None):
    proto = json.load(open(proto_path))
    days, c, zl, don = est.load(results)
    T, C = c["treated"], c["comparison"]
    launch = dt.date.fromisoformat(proto["launch"])
    pdates = est.placebo_dates(proto)
    fns = {
        "before_after": lambda t: est.before_after(T, t),
        "did": lambda t: est.did(T, C, t),
        "synthetic_control": lambda t: est.synth(T, don, t)["d"],
        "did_vs_manhattan_rest": lambda t: est.did(T, c["comparison_manhattan"], t),
        "did_vs_outer": lambda t: est.did(T, c["comparison_outer"], t),
    }
    x = np.array([(t - pdates[0]).days / 365.25 for t in pdates])
    out = {"change": "Change 1, after the results: exploratory placebo diagnostics; no scored result changed",
           "latest_n": LATEST, "latest_anchor_first": str(pdates[-LATEST]),
           "anchor_first": str(pdates[0]), "anchor_last": str(pdates[-1]),
           "windows_first_day": str(pdates[0] - dt.timedelta(days=est.W)),
           "windows_last_day": str(pdates[-1] + dt.timedelta(days=est.W - 1)), "methods": {}}
    for k, f in fns.items():
        dL = f(launch)
        dp = np.array([f(t) for t in pdates])
        med, med_latest = float(np.median(dp)), float(np.median(dp[-LATEST:]))
        slope = float(np.polyfit(x, 100 * (np.exp(dp) - 1), 1)[0])
        out["methods"][k] = {
            "launch_pct": est.pct(dL), "placebo_median_pct": est.pct(med),
            "adjusted_by_median_pct": est.pct(dL - med),
            "placebo_median_latest_pct": est.pct(med_latest),
            "adjusted_by_latest_pct": est.pct(dL - med_latest),
            "placebo_first_pct": est.pct(dp[0]), "placebo_last_pct": est.pct(dp[-1]),
            "drift_points_per_year": round(slope, 2),
        }
    out["fee_share_after"] = None
    if agg and os.path.exists(agg) and any(n.endswith(".parquet") for n in os.listdir(agg)):
        import duckdb
        import build_series
        import csv
        z = json.load(open(zones))
        fee, boundary = [int(v) for v in z["fee_zone_location_ids"]], [int(v) for v in z["boundary_location_ids"]]
        man = [int(r["LocationID"]) for r in csv.DictReader(open(lookup)) if r["Borough"] == "Manhattan"]
        treated, comparison, _ = build_series.group_sql(fee, boundary, man)
        con = duckdb.connect()
        con.execute("SET memory_limit='2GB'; SET threads=2")
        a, b = str(launch), str(launch + dt.timedelta(days=est.W - 1))
        q = (f"SELECT sum(fee_trips) FILTER (WHERE {{g}}) / sum(trips) FILTER (WHERE {{g}}) FROM "
             f"read_parquet('{agg}/hvfhv-*.parquet') WHERE day BETWEEN DATE '{a}' AND DATE '{b}'")
        out["fee_share_after"] = {
            "treated": round(float(con.execute(q.format(g=treated)).fetchone()[0]), 4),
            "comparison": round(float(con.execute(q.format(g=comparison)).fetchone()[0]), 4),
            "excluded": round(float(con.execute(q.format(g=f"NOT {treated} AND NOT {comparison}")).fetchone()[0]), 4),
        }
    out["treated_monthly_after"] = round(statistics.fmean(T[est.idx(launch):est.idx(launch) + est.W]) * 365.25 / 12)
    with open(f"{results}/change1-diagnostics.json", "w", encoding="utf-8") as fh:
        json.dump(out, fh, indent=1)
    return out


if __name__ == "__main__":
    o = run(*sys.argv[1:6])
    print(json.dumps(o, indent=1))
