"""The consumer KPI tree's fourth version: the page's recommended workflow, scored. A team measures the lasting point's lift with a
holdout and prices it with the arithmetic's value per point; this reads the lift the first world's half holdout measures at months 3,
6 and 12, prices it on both paths, and scores it against the truth beside the scaled test. A 10% holdout by scaling, not run.
Declared in DESIGN-kpitree-v4.md and protocol-kpitree-v4.json before any of this was computed.

No new lever is run: the half-holdout arm of the lasting point, already run in every world for its clocks, is repeated with the same
seeds and code to read its tables, and must return the stored clocks exactly. Resumable: one done-marker per world, written atomically.

    .venv/bin/python -I revfc/kpitree_v4.py run <work folder> [--procs 4] [--limit N]
    .venv/bin/python -I revfc/kpitree_v4.py aggregate <work folder>

The scoring reads only results/kpitree-v4-worlds.csv, so it replays from the download with no 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_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

RESULTS = ROOT / "results" / "kpitree-v4-results.json"
WORLDS = ROOT / "results" / "kpitree-v4-worlds.csv"
Z_KEYS = ("pooled", "cluster", "randomised", "revenue")


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


# ------------------------------------------------------------------ the measured lift


def holdout_tables(seed: int, pro: dict, lasting: float) -> dict:
    """The lasting point's half-holdout run, repeated as the second version ran it, from the no-change run's snapshot."""
    start, H = int(pro["levers"]["start_month"]), int(pro["levers"]["horizon_months"])
    w = VW.WorldV2(pro, seed, trace=True)
    w.run(snapshot_at=(start,), stop=start)
    return w.run(VW.Lever(start=start, lapse=lasting, holdout=True), stop=start - 1 + H)["ho"]


def measured_lift(kpi_n: np.ndarray, kpi_x: np.ndarray, a: int, k: int) -> float:
    """Treated retained over eligible, summed over months a to k since the change (1-based, inclusive), minus the held-out arm's, in
    points. Rows are months since the change; column 1 is the treated arm and column 0 the held-out arm, as in the clocks."""
    n = np.asarray(kpi_n, dtype=float)[a - 1:k].sum(axis=0)
    x = np.asarray(kpi_x, dtype=float)[a - 1:k].sum(axis=0)
    p = x / n
    return float((p[1] - p[0]) * 100)


def realised_lift(retention_points: list, a: int, k: int) -> float:
    """The lever's lift over months a to k from the stored lever and no-change runs, in points."""
    return float(np.nanmean(np.asarray(retention_points, dtype=float)[a - 1:k]))


def score_world(seed: int, pro: dict, lasting: float, stored_clocks: dict) -> dict:
    start, H = int(pro["levers"]["start_month"]), int(pro["levers"]["horizon_months"])
    s0 = start - 1
    ho = holdout_tables(seed, pro, lasting)
    z = VP.holdout_clocks(ho, start, H)
    tol = float(load_v4()["checks"]["z_atol"])
    match = {k: bool(np.allclose(z[k], stored_clocks[k], atol=tol)) for k in Z_KEYS}
    kpi_n = np.asarray(ho["kpi_n"], dtype=float)[s0:s0 + H]
    kpi_x = np.asarray(ho["kpi_x"], dtype=float)[s0:s0 + H]
    return KT.rnd({"seed": seed, "z_match": match, "kpi_n": kpi_n.tolist(), "kpi_x": kpi_x.tolist()}, 4)


def _do(job: tuple) -> str:
    seed, lasting, out, stored = job
    out = Path(out)
    if out.exists() and out.stat().st_size > 0:
        return out.name
    KT._write_atomic(out, score_world(seed, VW.load_protocol(), lasting, stored))
    return out.name


def run(work: Path, procs: int, limit: int | None) -> int:
    pro, pv = VW.load_protocol(), K2.load_v2()
    main_seed = int(pro["worlds"]["main_seed"])
    lasting = float(json.loads((work / "v2-calibration.json").read_text())["lasting_logit"])
    jobs = []
    for i in range(int(pv["complete_declared"]["worlds"])):
        s = main_seed + i
        stored = json.loads((work / f"v2-world-{s}.json").read_text())["clocks"]["lasting"]
        jobs.append((s, lasting, str(work / f"v4-world-{s}.json"), {k: stored[k] for k in Z_KEYS}))
    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


# ------------------------------------------------------------------ scoring, from the per-world file alone


def small_scale(cfg: dict) -> float:
    s = float(cfg["share"])
    return math.sqrt((1 / (1 - s) + 1 / s) / (2 / float(cfg["half_share"])))


def _row(truth: list, priced: list, test: list) -> dict:
    t, a, e = (np.array(x, dtype=float) for x in (truth, priced, test))
    return {"priced_over_truth": float((a / t).mean()), "test_over_truth": float((e / t).mean()), "mae_priced": float(np.abs(a - t).mean()), "mae_test": float(np.abs(e - t).mean()),
            "priced_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 score(rows: list, cfg: dict) -> dict:
    """Every cell the design declares, from the rows of results/kpitree-v4-worlds.csv."""
    f = small_scale(cfg["small_holdout"])
    ks = [int(k) for k in cfg["lift"]["read_at_months"]]
    froms = (int(cfg["lift"]["from_month"]), int(cfg["lift"]["from_month_alternative"]))
    truth = [float(r["truth_12"]) for r in rows]
    out: dict = {"scale": f, "n": len(rows), "one_point": {}, "priced": {}, "lift": {}}
    for path in ("true_path", "forecast_path"):
        arith, test = [float(r[f"arith_{path}_12"]) for r in rows], [float(r[f"test_{path}_12"]) for r in rows]
        out["one_point"][path] = _row(truth, arith, test)
        for a in froms:
            for k in ks:
                hat = [float(r[f"measured_{a}_{k}"]) for r in rows]
                real = [float(r[f"realised_{a}_{k}"]) for r in rows]
                small = [x + f * (h - x) for h, x in zip(hat, real)]
                cell = out["priced"].setdefault(f"from_{a}", {}).setdefault(str(k), {})
                cell[path] = {"half": _row(truth, [p * h for p, h in zip(arith, hat)], test), "small": _row(truth, [p * s for p, s in zip(arith, small)], test)}
    for a in froms:
        for k in ks:
            hat = np.array([float(r[f"measured_{a}_{k}"]) for r in rows])
            real = np.array([float(r[f"realised_{a}_{k}"]) for r in rows])
            err = hat - real
            out["lift"].setdefault(f"from_{a}", {})[str(k)] = {"measured": KT.summary(hat), "realised_mean": float(real.mean()), "error_mean": float(err.mean()), "error_sd": float(err.std(ddof=1)),
                                                              "small_sd": float(f * err.std(ddof=1))}
    return out


def after_the_results(rows: list, cfg: dict) -> dict:
    """Readings decided after the declared ones were read, labelled so on the page and kept out of every prediction.

    small_recentred: the declared 10% scaling multiplies the half holdout's whole error by 1.67, but that error is not centred on
    the realised lift (the "unbiased" prediction failed: the holdout takes in only users active at the change). Here only the
    scatter around the mean error is scaled, so a 10% holdout keeps the same mean error and 1.67 times the spread.
    spread: each world's priced value over its truth, per path, for the half holdout read from month 2."""
    f = small_scale(cfg["small_holdout"])
    a = int(cfg["lift"]["from_month"])
    truth = [float(r["truth_12"]) for r in rows]
    out: dict = {"small_recentred": {}, "spread": {}}
    for k in [int(x) for x in cfg["lift"]["read_at_months"]]:
        hat = np.array([float(r[f"measured_{a}_{k}"]) for r in rows])
        real = np.array([float(r[f"realised_{a}_{k}"]) for r in rows])
        b = float((hat - real).mean())
        small = real + b + f * (hat - real - b)
        for path in ("true_path", "forecast_path"):
            arith, test = [float(r[f"arith_{path}_12"]) for r in rows], [float(r[f"test_{path}_12"]) for r in rows]
            out["small_recentred"].setdefault(str(k), {})[path] = _row(truth, [p * x for p, x in zip(arith, small)], test)
            ratio = [p * h / t for p, h, t in zip(arith, hat, truth)]
            test_ratio = [e / t for e, t in zip(test, truth)]
            out["spread"].setdefault(str(k), {})[path] = {"priced": {**KT.summary(ratio), "min": float(min(ratio)), "max": float(max(ratio))},
                                                         "test": {**KT.summary(test_ratio), "min": float(min(test_ratio)), "max": float(max(test_ratio))}}
    return out


def predictions_v4(res: dict, cfg: dict) -> dict:
    b = cfg["bars"]
    p = res["priced"][f"from_{int(cfg['lift']['from_month'])}"]
    h12, h3 = p["12"]["true_path"]["half"], p["3"]["true_path"]["half"]
    s12, s3 = p["12"]["true_path"]["small"], p["3"]["true_path"]["small"]
    bias = res["lift"][f"from_{int(cfg['lift']['from_month'])}"]["12"]["error_mean"]
    yes = lambda x: "supported" if x else "not supported"  # noqa: E731
    stays = all(p["12"][path]["half"]["priced_closer"] > res["n"] / 2 for path in ("true_path", "forecast_path"))
    return {"half_12": yes(h12["priced_closer"] >= b["closer_worlds"] and h12["mae_priced"] < h12["mae_test"]), "half_3_worse": yes(h3["mae_priced"] > h12["mae_priced"]),
            "small_12": yes(s12["mae_priced"] < s12["mae_test"]), "small_3": yes(s3["priced_closer"] < b["closer_worlds"]), "unbiased": yes(abs(bias) <= b["bias_points"]),
            "advice": "stays" if stays else "changes"}


def results_from_rows(rows: list) -> dict:
    cfg = load_v4()
    res: dict = {"version": 4, "worlds": len(rows)}
    res.update(score(rows, cfg))
    res["checks"] = {"z_match_worlds": int(sum(1 for r in rows if r["z_match"] == "True")), "one_point_closer_true_path": res["one_point"]["true_path"]["priced_closer"],
                     "one_point_closer_forecast_path": res["one_point"]["forecast_path"]["priced_closer"]}
    res["checks"]["one_point_matches_third_version"] = (res["checks"]["one_point_closer_true_path"] == int(cfg["checks"]["one_point_closer_true_path"])
                                                        and res["checks"]["one_point_closer_forecast_path"] == int(cfg["checks"]["one_point_closer_forecast_path"]))
    res["predictions"] = predictions_v4(res, cfg)
    res["after_the_results"] = after_the_results(rows, cfg)
    return KT.rnd(res, 5)


def read_rows() -> list:
    with WORLDS.open(encoding="utf-8") as f:
        return list(csv.DictReader(f))


def aggregate(work: Path) -> int:
    pro, pv, cfg = VW.load_protocol(), K2.load_v2(), load_v4()
    main_seed = int(pro["worlds"]["main_seed"])
    seeds = [main_seed + i for i in range(int(pv["complete_declared"]["worlds"]))]
    ks = [int(k) for k in cfg["lift"]["read_at_months"]]
    froms = (int(cfg["lift"]["from_month"]), int(cfg["lift"]["from_month_alternative"]))
    with (ROOT / "results" / "kpitree-v2-worlds.csv").open(encoding="utf-8") as f:
        truth = {int(r["seed"]): r for r in csv.DictReader(f) if r["world"] == "first" and r["lever"] == "lasting"}
    with (ROOT / "results" / "kpitree-v3-worlds.csv").open(encoding="utf-8") as f:
        paths = {int(r["seed"]): r for r in csv.DictReader(f) if r["world"] == "first" and r["lever"] == "lasting"}
    head = ["seed", "z_match", "truth_12", "arith_true_path_12", "test_true_path_12", "arith_forecast_path_12", "test_forecast_path_12",
            *[f"measured_{a}_{k}" for a in froms for k in ks], *[f"realised_{a}_{k}" for a in froms for k in ks]]
    out = [head]
    for s in seeds:
        r4 = json.loads((work / f"v4-world-{s}.json").read_text())
        v2 = json.loads((work / f"v2-world-{s}.json").read_text())
        rp = v2["arms"]["lasting"]["retention_points"]
        p = paths[s]
        out.append([s, all(r4["z_match"].values()), truth[s]["truth_12"], p["arith_true_path_12"], p["test_true_path_12"], p["arith_forecast_path_12"], p["test_forecast_path_12"],
                    *[round(measured_lift(r4["kpi_n"], r4["kpi_x"], a, k), 5) for a in froms for k in ks], *[round(realised_lift(rp, a, k), 5) for a in froms for k in ks]])
    with WORLDS.open("w", newline="", encoding="utf-8") as f:
        csv.writer(f, lineterminator="\n").writerows(out)
    res = results_from_rows(read_rows())
    # the exact lever strength the repeated runs used (the second version's results print it rounded), so one world can be re-run
    res["inputs"] = {"lasting_logit": float(json.loads((work / "v2-calibration.json").read_text())["lasting_logit"])}
    RESULTS.write_text(json.dumps(res, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
    ok = res["checks"]["z_match_worlds"] == len(seeds) and res["checks"]["one_point_matches_third_version"]
    print(f"AGGREGATE VERDICT: {'PASS' if ok else 'FAIL'}", hashlib.sha256(RESULTS.read_bytes()).hexdigest(), hashlib.sha256(WORLDS.read_bytes()).hexdigest())
    return 0 if ok else 1


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("--limit", type=int, default=None)
    a = ap.parse_args()
    return run(a.work, a.procs, a.limit) if a.cmd == "run" else aggregate(a.work)


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