"""The consumer KPI tree's third version: both estimates on a forecast path, a 10% holdout by scaling, the noise band without the
price step, and readings off stored runs. Declared in DESIGN-kpitree-v3.md and protocol-kpitree-v3.json before any of this was
computed. No lever is run: the base runs are repeated only to read their tables.

Resumable: one done-marker per world or seed in the work folder, written atomically. The held-out part needs
revfc/kpitree_heldout_world.py, which the public download leaves out.

    .venv/bin/python -I revfc/kpitree_v3.py run <work folder> [--procs 4] [--only worlds|heldout] [--limit N]
    .venv/bin/python -I revfc/kpitree_v3.py aggregate <work folder>
"""
from __future__ import annotations

import argparse
import csv
import hashlib
import json
import math
import multiprocessing as mp
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 kpitree as KT  # noqa: E402
from revfc import kpitree_planner as PL  # noqa: E402
from revfc import kpitree_v2 as K2  # noqa: E402
from revfc import kpitree_v2_planner as VP  # noqa: E402
from revfc import kpitree_v2_world as VW  # noqa: E402
from revfc.kpitree_world import World, load_protocol  # noqa: E402

RESULTS = ROOT / "results" / "kpitree-v3-results.json"
WORLDS = ROOT / "results" / "kpitree-v3-worlds.csv"
FORECAST_KEYS = ("signups", "new", "resurrected", "retained", "mau", "revenue")


def load_v3() -> dict:
    return json.loads((ROOT / "protocol-kpitree-v3.json").read_text(encoding="utf-8"))


# ------------------------------------------------------------------ the forecast path


def _grown(x: np.ndarray, s0: int, months: int, level: int, year: int) -> np.ndarray:
    """A line's forecast: its last `level` months' mean, growing at the monthly rate that mean implies against the same months a year
    earlier, compounding from the middle of those months."""
    now, then = float(x[s0 - level:s0].mean()), float(x[s0 - level - year:s0 - year].mean())
    g = (now / then) ** (1 / year)
    return np.array([now * g ** (k + (level + 1) / 2) for k in range(months)])


def forecast_tables(t: dict, start: int, months: int, cfg: dict) -> dict:
    """A copy of a base run's tables with every month from the change onward replaced by a forecast made only from earlier months.
    The monthly lines the estimates read are the only tables replaced; the cohort and test tables are as they were."""
    s0 = start - 1
    m = t["m"]
    level, year = int(cfg["level_months"]), int(cfg["year_back_months"])
    signups = _grown(m["signups"], s0, months, level, year)
    new, resurrected = _grown(m["new"], s0, months, level, year), _grown(m["resurrected"], s0, months, level, year)
    back = int(cfg["retention_months"])
    ret = float(np.mean([m["retained"][mo] / m["mau"][mo - 1] for mo in range(s0 - back, s0)]))
    arpu_months = int(cfg["arpu_months"])
    arpu = float(np.mean(m["revenue"][s0 - arpu_months:s0] / m["mau"][s0 - arpu_months:s0]))
    fm = {k: np.array(v, dtype=float) for k, v in m.items()}
    prev = float(m["mau"][s0 - 1])
    for k in range(months):
        mo = s0 + k
        kept = prev * ret
        mau = kept + new[k] + resurrected[k]
        fm["signups"][mo], fm["new"][mo], fm["resurrected"][mo] = signups[k], new[k], resurrected[k]
        fm["retained"][mo], fm["mau"][mo], fm["revenue"][mo] = kept, mau, arpu * mau
        prev = mau
    out = dict(t)
    out["m"] = fm
    return out


def estimate_sums(t: dict, start: int, months: int, window: tuple, h: int) -> dict:
    """The four estimates the rows score, each summed over h months, from the same code the scored runs used."""
    est = PL.value_estimates(t, start, months, True)
    lasting = VP.retention_estimate(t, start, months, window)
    return {"arith_activation": float(est["arith_activation"][:h].sum()), "arith_retention": float(est["arith_retention"][:h].sum()),
            "test_activation": float(est["test_activation"][:h].sum()), "test_retention": float(lasting[:h].sum())}


def score_tables(seed: int, t: dict, pro: dict, pv: dict, cfg: dict) -> dict:
    start, H = int(pro["levers"]["start_month"]), int(pro["levers"]["horizon_months"])
    window = tuple(pv["lasting_first_stage_months"])
    h = int(cfg["score_months"])
    fc = forecast_tables(t, start, H, cfg)
    s0 = start - 1
    actual, guess = t["m"]["revenue"][s0:s0 + h], fc["m"]["revenue"][s0:s0 + h]
    return KT.rnd({"seed": seed, "true_path": estimate_sums(t, start, H, window, h), "forecast_path": estimate_sums(fc, start, H, window, h),
                   "revenue_error_pct": float(np.mean(np.abs(guess - actual) / actual) * 100), "revenue_bias_pct": float((guess.sum() - actual.sum()) / actual.sum() * 100)})


_HELD = None


def _do(job: tuple) -> str:
    global _HELD
    kind, seed, out = job
    out = Path(out)
    if out.exists() and out.stat().st_size > 0:
        return out.name
    pro, pv, cfg = load_protocol(), K2.load_v2(), load_v3()["forecast"]
    if kind == "world":
        w = World(pro, seed)
        t = PL.arrays(w.planner_tables(w.run()))
    else:
        if _HELD is None:
            _HELD = VW.heldout_module()
        t = PL.arrays(_HELD.run_world(seed))
    KT._write_atomic(out, score_tables(seed, t, pro, pv, cfg))
    return out.name


def run(work: Path, procs: int, only: str, limit: int | None) -> int:
    pro, pv = load_protocol(), K2.load_v2()
    main_seed = int(pro["worlds"]["main_seed"])
    jobs = []
    if only in ("worlds", "all"):
        jobs += [("world", main_seed + i, str(work / f"v3-world-{main_seed + i}.json")) for i in range(int(pv["complete_declared"]["worlds"]))]
    if only in ("heldout", "all"):
        jobs += [("heldout", main_seed + i, str(work / f"v3-heldout-{main_seed + i}.json")) for i in range(int(pro["worlds"]["heldout_seeds"]))]
    todo = [j for j in jobs if not (Path(j[2]).exists() and Path(j[2]).stat().st_size > 0)]
    if limit is not None:
        todo = todo[:limit]
    print(f"{len(jobs)} jobs, {len(todo)} to do", flush=True)
    if procs <= 1:
        for j in todo:
            print(_do(j), flush=True)
    else:
        with mp.get_context("spawn").Pool(procs) as pool:
            for name in pool.imap_unordered(_do, todo):
                print(name, flush=True)
    left = [j for j in jobs if not Path(j[2]).exists()]
    print(f"RUN VERDICT: {'DONE' if not left else 'PARTIAL'} ({len(jobs) - len(left)} of {len(jobs)} done)")
    return 0


# ------------------------------------------------------------------ aggregate


def _row(truth: list, arith: list, test: list) -> dict:
    t, a, e = (np.array(x, dtype=float) for x in (truth, arith, test))
    return {"arith_over_truth": float((a / t).mean()), "test_over_truth": float((e / t).mean()), "mae_arith": float(np.abs(a - t).mean()), "mae_test": float(np.abs(e - t).mean()),
            "arith_closer": int((np.abs(a - t) < np.abs(e - t)).sum()), "test_closer": int((np.abs(e - t) < np.abs(a - t)).sum()), "n": len(t)}


def forecast_block(work: Path, seeds: list, held: list) -> dict:
    with (ROOT / "results" / "kpitree-v2-worlds.csv").open(encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    truth = {(r["world"], r["lever"], int(r["seed"])): r for r in rows}
    runs = {("first", s): json.loads((work / f"v3-world-{s}.json").read_text()) for s in seeds}
    runs.update({("heldout", s): json.loads((work / f"v3-heldout-{s}.json").read_text()) for s in held})
    out: dict = {"rows": {}, "checks": {}}
    matches = n = 0
    per_world = [["world", "seed", "lever", "truth_12", "arith_true_path_12", "test_true_path_12", "arith_forecast_path_12", "test_forecast_path_12", "forecast_revenue_abs_error_pct", "forecast_revenue_bias_pct"]]
    for world, lever, name, ss in (("first", "activation", "activation", seeds), ("first", "lasting", "retention", seeds), ("heldout", "activation", "activation", held), ("heldout", "reminder_active", "retention", held)):
        tr = [float(truth[(world, lever, s)]["truth_12"]) for s in ss]
        block = {}
        for path in ("true_path", "forecast_path"):
            block[path] = _row(tr, [runs[(world, s)][path][f"arith_{name}"] for s in ss], [runs[(world, s)][path][f"test_{name}"] for s in ss])
        for s in ss:
            r, stored = runs[(world, s)]["true_path"], truth[(world, lever, s)]
            n += 1
            matches += int(abs(r[f"arith_{name}"] - float(stored["arith_12"])) < 0.02 and abs(r[f"test_{name}"] - float(stored["test_12"])) < 0.02)
            fc, run_row = runs[(world, s)]["forecast_path"], runs[(world, s)]
            per_world.append([world, s, lever, stored["truth_12"], round(r[f"arith_{name}"], 2), round(r[f"test_{name}"], 2), round(fc[f"arith_{name}"], 2), round(fc[f"test_{name}"], 2), round(run_row["revenue_error_pct"], 4), round(run_row["revenue_bias_pct"], 4)])
        out["rows"][f"{world}_{lever}"] = block
    out["checks"] = {"true_path_matches_stored": matches, "true_path_rows": n}
    with WORLDS.open("w", newline="", encoding="utf-8") as f:
        csv.writer(f, lineterminator="\n").writerows(per_world)
    for world, ss in (("first", seeds), ("heldout", held)):
        out[f"revenue_error_{world}"] = {"mean_abs_pct": float(np.mean([runs[(world, s)]["revenue_error_pct"] for s in ss])), "bias": KT.summary([runs[(world, s)]["revenue_bias_pct"] for s in ss])}
    return out


def _phi(x: float) -> float:
    return 0.5 * (1 + math.erf(x / math.sqrt(2)))


def small_clock(zs: list, scale: float, z: float, power: float) -> dict:
    a = np.array(zs, dtype=float)
    mean_z = a.mean(axis=0)
    share = [_phi(m / scale - z) for m in mean_z]
    first = next((k + 1 for k, s in enumerate(share) if s >= power), None)
    counts = (a / scale > z).sum(axis=0)
    return {"first_month": first, "share_by_month_pct": [s * 100 for s in share], "share_24_pct": share[-1] * 100, "share_12_pct": share[11] * 100, "count_24": int(counts[-1]), "count_at_first": int(counts[first - 1]) if first else None, "n": a.shape[0], "half_mean_z_24": float(mean_z[-1])}


def small_holdout_block(F: list, V: list, cfg: dict) -> dict:
    s = float(cfg["share"])
    scale = math.sqrt((1 / (1 - s) + 1 / s) / (2 / float(cfg["half_share"])))
    z, power = float(cfg["z"]), float(cfg["power"])
    return {"scale": scale, "lasting_own": small_clock([v["clocks"]["lasting"]["cluster"] for v in V], scale, z, power), "activation_own": small_clock([f["clocks"]["activation"]["kpi"] for f in F], scale, z, power),
            "lasting_revenue": small_clock([v["clocks"]["lasting"]["revenue"] for v in V], scale, z, power), "activation_revenue": small_clock([f["clocks"]["activation"]["revenue"] for f in F], scale, z, power)}


def noise_block(F: list, V: list, cfg: dict) -> dict:
    out_months = [int(x) for x in cfg["left_out_months"]]
    first_month = out_months[0]
    keep = [i for i in range(12) if i + first_month not in out_months]
    q = float(cfg["quantile"])
    errs = np.array([f["noise"]["errors"] for f in F], dtype=float)
    declared = [float(f["noise"]["half_width_pct"]) for f in F]
    again = [float(np.quantile(e, q)) for e in errs]
    without = [float(np.quantile(e[keep], q)) for e in errs]
    base = [f["base"]["revenue"] for f in F]
    arms = {"lasting": [v["arms"]["lasting"]["revenue"] for v in V], "first_lever": [f["arms"]["retention"]["revenue"] for f in F], "activation": [f["arms"]["activation"]["revenue"] for f in F]}
    return {"declared": {"mean": float(np.mean(declared)), "lo": float(np.min(declared)), "hi": float(np.max(declared))}, "recomputes_declared": bool(np.allclose(declared, again, atol=2e-3)),
            "without_step": {"mean": float(np.mean(without)), "lo": float(np.min(without)), "hi": float(np.max(without))}, "mean_error_by_month": {str(first_month + i): float(errs[:, i].mean()) for i in range(12)},
            "lines_without_step": {k: K2.line_block(r, base, without) for k, r in arms.items()}, "lines_declared": {k: K2.line_block(r, base, declared) for k, r in arms.items()}}


def readings_block(F: list, V: list, work: Path, pro: dict) -> dict:
    with (ROOT / "results" / "kpitree-v2-worlds.csv").open(encoding="utf-8") as f:
        rows = {int(r["seed"]): r for r in csv.DictReader(f) if r["world"] == "first" and r["lever"] == "lasting"}
    lifts = [float(np.nanmean(v["arms"]["lasting"]["retention_points"][1:12])) for v in V]
    seeds = [v["seed"] for v in V]
    per = [float(rows[s]["truth_12"]) / x for s, x in zip(seeds, lifts)]
    out = {"main_truth": {"activated": F[0]["truth_age3"]["activation"] * 100, "first_repeat": F[0]["truth_age3"]["first_repeat"] * 100, "seed": F[0]["seed"]},
           "per_realised": {"value": KT.summary(per), "lift_mean": float(np.mean(lifts)), "arith_over_truth": float(np.mean([float(rows[s]["arith_12"]) / x for s, x in zip(seeds, per)])), "test_over_truth": float(np.mean([float(rows[s]["test_12"]) / x for s, x in zip(seeds, per)]))}}
    frozen = {}
    for p in sorted(work.glob("cell-*.json")):
        d = json.loads(p.read_text())
        frozen[(d["key"], d["end"], d["seed"])] = d
    cells: dict = {}
    for p in sorted(work.glob("v2-cell-*.json")):
        d = json.loads(p.read_text())
        c = cells.setdefault(d["key"], {"label": pro["sweep"][d["key"]]["label"], "low": {"retention": [], "activation": []}, "high": {"retention": [], "activation": []}})
        c[d["end"]]["retention"].append(d["value_per_point"])
        c[d["end"]]["activation"].append(frozen[(d["key"], d["end"], d["seed"])]["activation"])
    sweep = {k: {"label": c["label"], **{end: {"retention": float(np.mean(c[end]["retention"])), "activation": float(np.mean(c[end]["activation"])), "n": len(c[end]["retention"])} for end in ("low", "high")}} for k, c in cells.items()}
    rv = [s[e]["retention"] for s in sweep.values() for e in ("low", "high")]
    av = [s[e]["activation"] for s in sweep.values() for e in ("low", "high")]
    out["sweep"] = sweep
    out["sweep_range"] = {"retention_min": min(rv), "retention_max": max(rv), "activation_min": min(av), "activation_max": max(av)}
    return out


def predictions_v3(res: dict, cfg: dict) -> dict:
    b = cfg["bars"]
    rows = res["forecast"]["rows"]
    worse = sum(1 for r in rows.values() if r["forecast_path"]["mae_arith"] > r["true_path"]["mae_arith"])
    closer = {k: r["forecast_path"]["arith_closer"] > r["forecast_path"]["test_closer"] for k, r in rows.items()}
    order = closer == {k: k != "first_activation" for k in rows}
    sm = res["small_holdout"]
    rev = sm["lasting_revenue"]["share_24_pct"]
    lo, ao = sm["lasting_own"]["first_month"], sm["activation_own"]["first_month"]
    own = lo is not None and ao is not None and lo <= b["own_kpi_lasting_by"] and ao <= b["own_kpi_activation_by"] and lo < ao
    no = res["noise"]
    drop = no["declared"]["mean"] - no["without_step"]["mean"]
    above = no["lines_without_step"]["lasting"]["worlds_above_own_band_24"]
    yes = lambda x: "supported" if x else "not supported"  # noqa: E731
    return {"forecast_costs": yes(worse >= b["forecast_rows_worse"]), "forecast_rows_worse": worse, "order_survives": yes(order), "order_by_row": closer, "small_revenue": yes(b["revenue_share_lo"] <= rev <= b["revenue_share_hi"]),
            "small_own": yes(own), "band": yes(drop >= b["band_drop_points"] and above > b["band_worlds_above"]), "band_drop": drop, "band_worlds_above": above}


def aggregate(work: Path) -> int:
    pro, pv, cfg = load_protocol(), K2.load_v2(), load_v3()
    main_seed = int(pro["worlds"]["main_seed"])
    seeds = [main_seed + i for i in range(int(pv["complete_declared"]["worlds"]))]
    held = [main_seed + i for i in range(int(pro["worlds"]["heldout_seeds"]))]
    F = [json.loads((work / f"world-{s}.json").read_text()) for s in seeds]
    V = [json.loads((work / f"v2-world-{s}.json").read_text()) for s in seeds]
    res: dict = {"version": 3, "worlds": len(seeds), "heldout_seeds": len(held)}
    res["forecast"] = forecast_block(work, seeds, held)
    res["small_holdout"] = small_holdout_block(F, V, cfg["small_holdout"])
    res["noise"] = noise_block(F, V, cfg["noise_window"])
    res["readings"] = readings_block(F, V, work, pro)
    res["predictions"] = predictions_v3(res, cfg)
    RESULTS.write_text(json.dumps(KT.rnd(res, 5), indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
    print("AGGREGATE VERDICT: PASS", hashlib.sha256(RESULTS.read_bytes()).hexdigest())
    return 0


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=("run", "aggregate"))
    ap.add_argument("work", type=Path)
    ap.add_argument("--procs", type=int, default=4)
    ap.add_argument("--only", default="all", choices=("all", "worlds", "heldout"))
    ap.add_argument("--limit", type=int, default=None)
    a = ap.parse_args()
    return run(a.work, a.procs, a.only, a.limit) if a.cmd == "run" else aggregate(a.work)


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