"""Active-driver round: the cohort plan against the published trip-driver forecast and the naive baseline.

Follows DESIGN-drivers.md (committed before this file existed). Reads only committed tables (data/monthly.csv,
data/drivers-cohorts.csv) and the published forecasts file; no network. Writes results/drivers-results.json and
results/drivers-forecasts.csv. The published results files are read, never written.

    .venv/bin/python -I revfc/drivers_backtest.py [--out results]

Deterministic: the fits are least squares from fixed starts and the bootstrap uses the published seed and streams, so a
re-run reproduces both files byte for byte.
"""
from __future__ import annotations

import csv
import hashlib
import json
import sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from revfc import backtest as B  # noqa: E402
from revfc import model as M  # noqa: E402

COHORTS = ROOT / "data" / "drivers-cohorts.csv"
MONTHLY_DRIVERS = ROOT / "data" / "drivers-monthly.csv"
PUBLISHED_RESULTS = ROOT / "results" / "results.json"
PUBLISHED_FORECASTS = ROOT / "results" / "forecasts.csv"
MAX_AGE = 36                      # ages 0..35, then the 36+ row (index 36)
RET_WINDOWS = {"12": 12, "6": 6, "24": 24}
MAIN_RET = "12"
METHODS = ("cohort", "driver", "naive")
PAIRS = (("cohort", "driver"), ("cohort", "naive"), ("driver", "naive"))
PARTS = ("new", "retention", "per_driver", "per_trip")
CURVE_YEARS = ("2019", "2020", "2021", "2022", "2023", "2024", "2025")


# ------------------------------------------------------------------ data

def load_cohorts(path: Path = COHORTS) -> dict:
    """Month -> array of active drivers by age (0..35, then 36+ at index 36)."""
    out: dict = {}
    with path.open(encoding="utf-8", newline="") as fh:
        for r in csv.DictReader(fh):
            row = out.setdefault(r["month"], np.zeros(MAX_AGE + 1))
            row[MAX_AGE if r["age"] == "36+" else int(r["age"])] = float(r["active"])
    return dict(sorted(out.items()))


def pieces(cohorts: dict, data: dict) -> dict:
    """Per month: new drivers N, surviving S, active A, trips T, trips per active driver q, revenue per trip r, revenue R."""
    out = {}
    for mo, ages in cohorts.items():
        T = float(sum(data[mo][s]["trips"] for s in M.SEGMENTS))
        R = M.revenue(data[mo])
        A = float(ages.sum())
        out[mo] = {"N": float(ages[0]), "S": float(ages[1:].sum()), "A": A, "T": T, "q": T / A, "r": R / T, "R": R}
    return out


def identity_check(p: dict) -> dict:
    worst, worst_month = 0.0, None
    for mo, x in p.items():
        gap = abs((x["N"] + x["S"]) * x["q"] * x["r"] - x["R"])
        if gap > worst:
            worst, worst_month = gap, mo
    return {"months": len(p), "max_abs_gap_usd": worst, "worst_month": worst_month}


# ------------------------------------------------------------------ the cohort plan

def ratios(cohorts: list[np.ndarray], o: int, window: int) -> np.ndarray:
    """One-month carry ratios by age from the last `window` transitions known at origin index o (u -> u + 1, u + 1 <= o).
    Index a in 0..34: age a to a + 1; index 35: (age 35 + 36+) to 36+."""
    us = range(max(0, o - window), o)
    num, den = np.zeros(MAX_AGE), np.zeros(MAX_AGE)
    for u in us:
        cur, nxt = cohorts[u], cohorts[u + 1]
        num[:MAX_AGE - 1] += nxt[1:MAX_AGE]
        den[:MAX_AGE - 1] += cur[:MAX_AGE - 1]
        num[MAX_AGE - 1] += nxt[MAX_AGE]
        den[MAX_AGE - 1] += cur[MAX_AGE - 1] + cur[MAX_AGE]
    return np.divide(num, den, out=np.zeros(MAX_AGE), where=den > 0)


def project(start: np.ndarray, rho: np.ndarray, new: np.ndarray) -> list[np.ndarray]:
    """Age rows for the next len(new) months: every row moves one age older times its ratio; age 0 is the new-driver
    forecast; age 35 and the 36+ row pool into 36+."""
    rows, cur = [], start.copy()
    for n in new:
        nxt = np.zeros(MAX_AGE + 1)
        nxt[0] = n
        nxt[1:MAX_AGE] = cur[:MAX_AGE - 1] * rho[:MAX_AGE - 1]
        nxt[MAX_AGE] = (cur[MAX_AGE - 1] + cur[MAX_AGE]) * rho[MAX_AGE - 1]
        rows.append(nxt)
        cur = nxt
    return rows


def choose_form(key: str, y: np.ndarray) -> dict:
    z = np.log(y)
    a_n, a_d = M.aicc(z, False), M.aicc(z, True)
    return {"form": "A,Ad,A" if a_d < a_n else "A,N,A", "aicc_ANA": a_n, "aicc_AAdA": a_d}


# ------------------------------------------------------------------ the run

def published_forecasts() -> dict:
    out = {}
    with PUBLISHED_FORECASTS.open(encoding="utf-8", newline="") as fh:
        for r in csv.DictReader(fh):
            if r["window"] == "expanding" and r["line"] == "revenue":
                out[(r["origin"], int(r["h"]))] = {k: float(r[k]) for k in ("actual", "driver", "direct", "naive")}
    return out


def run(data, months, p, cohort_rows, forms, pub_forms):
    series = M.model_inputs(data)
    pub = published_forecasts()
    o0, o1 = months.index(B.FIRST_ORIGIN), months.index(B.LAST_ORIGIN)
    N = np.array([p[m]["N"] for m in months])
    q = np.array([p[m]["q"] for m in months])
    rows, repro_gap = [], 0.0
    for o in range(o0, o1 + 1):
        steps = min(max(B.HORIZONS), len(months) - 1 - o)
        # (b) the published trip-driver forecast, recomputed with its frozen forms
        fc = {k: M.ets_forecast(k, series[k][: o + 1], pub_forms[k] == "A,Ad,A", steps) for k in M.DRIVERS}
        naive_t = M.naive_growth(series["T"][: o + 1], steps)
        # (a) the cohort plan's model pieces
        n_fc = M.ets_forecast("N", N[: o + 1], forms["N"]["form"] == "A,Ad,A", steps)
        q_fc = M.ets_forecast("q", q[: o + 1], forms["q"]["form"] == "A,Ad,A", steps)
        plans = {}
        for name, w in RET_WINDOWS.items():
            rho = ratios(cohort_rows, o, w)
            plans[name] = project(cohort_rows[o], rho, n_fc)
        for h in range(1, steps + 1):
            t = o + h
            d = {k: float(fc[k][h - 1]) for k in M.DRIVERS}
            d["w_solo"] = 1.0 - d["w_shared"]
            r_drv, _ = M.compose(d)
            t_drv = d["T"]
            r_hat = r_drv / t_drv
            ref = pub[(months[o], h)]
            repro_gap = max(repro_gap, abs(round(r_drv, 2) - ref["driver"]))
            act = p[months[t]]
            row = {"origin": months[o], "h": h, "target": months[t], "r_plan": r_hat,
                   "trips": {"actual": act["T"], "driver": t_drv, "naive": float(naive_t[h - 1])},
                   "revenue": {"actual": act["R"], "driver": r_drv, "naive": ref["naive"], "direct": ref["direct"]},
                   "cohort": {}}
            for name, rows_ in plans.items():
                ages = rows_[h - 1]
                a_hat = float(ages.sum())
                t_hat = a_hat * float(q_fc[h - 1])
                row["cohort"][name] = {"N": float(ages[0]), "S": float(ages[1:].sum()), "A": a_hat,
                                       "q": float(q_fc[h - 1]), "T": t_hat, "R": t_hat * r_hat}
            rows.append(row)
    return rows, repro_gap


def score(rows, line: str, ret: str) -> dict:
    out = {}
    for ri, regime in enumerate(B.REGIMES):
        out[regime] = {}
        for h in B.HORIZONS:
            sel = sorted((r for r in rows if r["h"] == h and B.regime_of(r["target"]) == regime),
                         key=lambda r: r["target"])
            if not sel:
                continue
            act = np.array([r[line]["actual"] for r in sel])
            key = "T" if line == "trips" else "R"
            val = {"cohort": np.array([r["cohort"][ret][key] for r in sel]),
                   "driver": np.array([r[line]["driver"] for r in sel]),
                   "naive": np.array([r[line]["naive"] for r in sel])}
            ape = {m: np.abs(val[m] / act - 1) * 100 for m in METHODS}
            signed = {m: (val[m] / act - 1) * 100 for m in METHODS}
            rng = np.random.default_rng([B.SEED, ri, h])
            idx = B.block_indices(len(sel), rng)
            cell = {"n": len(sel), "first_target": sel[0]["target"], "last_target": sel[-1]["target"]}
            for m in METHODS:
                boots = ape[m][idx].mean(axis=1)
                cell[m] = {"mape": float(ape[m].mean()), "lo": float(np.percentile(boots, 2.5)),
                           "hi": float(np.percentile(boots, 97.5)), "bias": float(signed[m].mean()),
                           "median_ape": float(np.median(ape[m]))}
            for a, b in PAIRS:
                diff = ape[a] - ape[b]
                boots = diff[idx].mean(axis=1)
                cell[f"{a}_minus_{b}"] = {"mean": float(diff.mean()), "lo": float(np.percentile(boots, 2.5)),
                                          "hi": float(np.percentile(boots, 97.5)),
                                          "months_a_better": int((diff < 0).sum())}
            out[regime][str(h)] = cell
    return out


def bridge_parts(act: dict, plan: dict) -> dict:
    return {"new": (act["N"] - plan["N"]) * plan["q"] * plan["r"],
            "retention": (act["S"] - plan["S"]) * plan["q"] * plan["r"],
            "per_driver": act["A"] * (act["q"] - plan["q"]) * plan["r"],
            "per_trip": act["T"] * (act["r"] - plan["r"])}


def bridges(rows, p, h: int) -> dict:
    per_month = []
    for r in rows:
        if r["h"] != h:
            continue
        c = r["cohort"][MAIN_RET]
        plan = {"N": c["N"], "S": c["S"], "A": c["A"], "q": c["q"], "r": r["r_plan"], "T": c["T"]}
        act = p[r["target"]]
        parts = bridge_parts(act, plan)
        miss = act["R"] - c["R"]
        per_month.append({"month": r["target"], "regime": B.regime_of(r["target"]), "actual": act["R"], "plan": c["R"],
                          "miss": miss, "miss_pct": (act["R"] / c["R"] - 1) * 100, "parts": parts,
                          "closure": sum(parts.values()) - miss, "largest": max(parts, key=lambda k: abs(parts[k]))})
    summary = {}
    for regime in B.REGIMES:
        rr = [x for x in per_month if x["regime"] == regime]
        summary[regime] = {"months": len(rr),
                           "largest_counts": {k: sum(1 for x in rr if x["largest"] == k) for k in PARTS},
                           "mean_abs_part": {k: float(np.mean([abs(x["parts"][k]) for x in rr])) for k in PARTS},
                           "biggest_misses": [x["month"] for x in sorted(rr, key=lambda x: -abs(x["miss_pct"]))[:3]]}
    return {"per_month": per_month, "summary": summary,
            "max_abs_closure": float(max(abs(x["closure"]) for x in per_month))}


def prediction(sc: dict) -> dict:
    c = sc["settled"]["3"]["cohort_minus_driver"]
    if c["hi"] < 0:
        verdict = "supported"
    elif c["mean"] < 0:
        verdict = "direction only"
    else:
        verdict = "not supported"
    return {"statement": "The cohort plan beats the published trip-driver forecast on revenue three months ahead in "
                         "the settled years.",
            "line": "revenue", "regime": "settled", "h": 3, "difference": c, "verdict": verdict}


def retention_curves(cohorts: dict) -> dict:
    """Per start year: active drivers at each age as a share of the same cohorts' active drivers at age 1, summed over
    the year's monthly cohorts observed at both ages (descriptive, not scored)."""
    months = list(cohorts)
    idx = {m: i for i, m in enumerate(months)}
    out = {}
    for year in CURVE_YEARS:
        starts = [m for m in months if m.startswith(year)]
        curve = {}
        for a in range(0, MAX_AGE):
            num = den = 0.0
            used = 0
            for c in starts:
                i1, ia = idx[c] + 1, idx[c] + a
                if i1 < len(months) and ia < len(months):
                    num += cohorts[months[ia]][a]
                    den += cohorts[months[i1]][1]
                    used += 1
            if used and den > 0:
                curve[str(a)] = {"share": num / den, "cohorts": used}
        out[year] = curve
    return out


def describe(p: dict, months: list[str]) -> dict:
    with MONTHLY_DRIVERS.open(encoding="utf-8", newline="") as fh:
        md = {r["month"]: r for r in csv.DictReader(fh)}
    ratio = {m: p[m]["T"] / float(md[m]["trips_reported"]) for m in months}
    pick = ("2019-08", "2020-10", "2022-12", "2025-08", "2026-08")
    return {"first_month": months[0], "last_month": months[-1], "months": len(months),
            "active": {m: p[m]["A"] for m in pick}, "new": {m: p[m]["N"] for m in pick},
            "listed": {m: float(md[m]["listed"]) for m in pick},
            "per_driver": {m: p[m]["q"] for m in pick},
            "new_share": {m: p[m]["N"] / p[m]["A"] for m in pick},
            "trips_ratio_min": min(ratio.values()), "trips_ratio_max": max(ratio.values()),
            "trips_ratio_max_month": max(ratio, key=ratio.get)}


def main(argv: list[str]) -> int:
    out = ROOT / (argv[argv.index("--out") + 1] if "--out" in argv else "results")
    out.mkdir(parents=True, exist_ok=True)
    data = M.load_monthly()
    months = list(data)
    cohorts = load_cohorts()
    if list(cohorts) != months:
        print("DRIVERS BACKTEST VERDICT: FAIL (the cohort table's months differ from the trips table's)")
        return 1
    p = pieces(cohorts, data)
    cohort_rows = [cohorts[m] for m in months]
    o0 = months.index(B.FIRST_ORIGIN)
    forms = {"N": choose_form("N", np.array([p[m]["N"] for m in months[: o0 + 1]])),
             "q": choose_form("q", np.array([p[m]["q"] for m in months[: o0 + 1]]))}
    pub = json.loads(PUBLISHED_RESULTS.read_text(encoding="utf-8"))
    pub_forms = {k: v["form"] for k, v in pub["forms"].items()}
    rows, repro_gap = run(data, months, p, cohort_rows, forms, pub_forms)
    res = {"declaration": {"design": "DESIGN-drivers.md", "first_origin": B.FIRST_ORIGIN, "last_origin": B.LAST_ORIGIN,
                           "horizons": list(B.HORIZONS), "regimes": B.REGIMES, "retention_windows": RET_WINDOWS,
                           "main_retention_window": MAIN_RET, "seed": B.SEED, "resamples": B.RESAMPLES,
                           "block": B.BLOCK, "max_age": MAX_AGE},
           "data": describe(p, months), "identity": identity_check(p), "forms": forms,
           "inputs_sha256": {"monthly_csv": hashlib.sha256(M.MONTHLY.read_bytes()).hexdigest(),
                             "drivers_cohorts_csv": hashlib.sha256(COHORTS.read_bytes()).hexdigest(),
                             "published_forecasts_csv": hashlib.sha256(PUBLISHED_FORECASTS.read_bytes()).hexdigest()},
           "windows": {}}
    for name in RET_WINDOWS:
        res["windows"][name] = {"revenue": score(rows, "revenue", name), "trips": score(rows, "trips", name)}
    main_rev = res["windows"][MAIN_RET]["revenue"]
    worst = 0.0
    for regime, hs in main_rev.items():
        for h, c in hs.items():
            worst = max(worst, abs(c["driver"]["mape"] - pub["windows"]["expanding"]["revenue"][regime][h]["driver"]["mape"]),
                        abs(c["naive"]["mape"] - pub["windows"]["expanding"]["revenue"][regime][h]["naive"]["mape"]))
    res["reproduction"] = {"forecasts_compared": len(rows), "max_abs_revenue_gap_usd": repro_gap,
                           "max_abs_mape_gap_vs_published": worst,
                           "matches": bool(repro_gap <= 0.01 and worst < 1e-5)}
    res["bridge"] = {"1": bridges(rows, p, 1), "3": bridges(rows, p, 3)}
    res["prediction"] = prediction(main_rev)
    res["retention_curves"] = retention_curves(cohorts)
    res["by_target"] = [{"target": r["target"], "h": r["h"], "regime": B.regime_of(r["target"]),
                         "actual": r["revenue"]["actual"], "cohort": r["cohort"][MAIN_RET]["R"],
                         "driver": r["revenue"]["driver"], "naive": r["revenue"]["naive"]} for r in rows]
    (out / "drivers-results.json").write_text(json.dumps(B.rnd(res), indent=1, sort_keys=True) + "\n",
                                              encoding="utf-8")
    with (out / "drivers-forecasts.csv").open("w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["retention_window", "origin", "h", "target", "line", "actual", "cohort", "driver", "naive"])
        for name in RET_WINDOWS:
            for r in rows:
                for line, key in (("trips", "T"), ("revenue", "R")):
                    w.writerow([name, r["origin"], r["h"], r["target"], line, f"{r[line]['actual']:.2f}",
                                f"{r['cohort'][name][key]:.2f}", f"{r[line]['driver']:.2f}", f"{r[line]['naive']:.2f}"])
    ok = res["reproduction"]["matches"] and res["identity"]["max_abs_gap_usd"] < 0.01 and \
        all(b["max_abs_closure"] < 0.01 for b in res["bridge"].values())
    print(f"DRIVERS BACKTEST VERDICT: {'PASS' if ok else 'FAIL'} ({len(rows)} origin-horizon rows, identity gap "
          f"{res['identity']['max_abs_gap_usd']:.6f} USD, published forecasts reproduced within "
          f"{repro_gap:.2f} USD, bridge closure {max(b['max_abs_closure'] for b in res['bridge'].values()):.6f} USD)")
    return 0 if ok else 1


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