"""The second version's corrected estimators: what a planner can compute from a test's users. Reads tables and user-level test
trajectories only, never a user's intent, so it runs on both worlds. Declared in DESIGN-kpitree-v2.md (C4 and C5).
"""
from __future__ import annotations

import math

import numpy as np

STREAM = 9001


# ------------------------------------------------------------------ the first stage and the rollout estimate, by window


def window_lift(t: dict, window: tuple) -> float:
    """Treated minus control monthly retention in test C, mean over months since its start, 1-based and inclusive."""
    e2m, c, g = t["e2m"], t["tests"]["e2"]["control"], t["tests"]["e2"]["treated"]
    out = []
    for k in range(window[0] - 1, window[1]):
        nt = g["n"] if k == 0 else e2m[1, k - 1, 0]
        nc = c["n"] if k == 0 else e2m[0, k - 1, 0]
        out.append(e2m[1, k, 2] / nt - e2m[0, k, 2] / nc)
    return float(np.mean(out))


def retention_weights(mau_before: float, enter: np.ndarray, h: int) -> np.ndarray:
    """The weight on test C's revenue difference at each month since its start, in the estimate's sum over h months."""
    u = np.zeros(h)
    for ell in range(h):
        u[ell] = mau_before + enter[: max(0, h - 1 - ell)].sum()
    return u


def activation_weights(s: np.ndarray, h: int) -> np.ndarray:
    """The weight on test A's revenue difference at each age, in the estimate's sum over h months."""
    return np.array([s[: h - a].sum() for a in range(h)])


def retention_estimate(t: dict, start: int, months: int, window: tuple) -> np.ndarray:
    """Test C's monthly estimate of one point, with the first stage over the given window."""
    m = t["m"]
    s0 = start - 1
    e2, e2m = t["tests"]["e2"], t["e2m"]
    d_r = e2m[1, :, 1] / e2["treated"]["n"] - e2m[0, :, 1] / e2["control"]["n"]
    enter = m["new"][s0:s0 + months] + m["resurrected"][s0:s0 + months]
    out = np.zeros(months)
    tau = window_lift(t, window)
    for k in range(months):
        v = m["mau"][s0 - 1] * d_r[k]
        for j in range(k):
            v += enter[j] * d_r[k - j - 1]
        out[k] = v * 0.01 / tau
    return out


# ------------------------------------------------------------------ the bootstrap of randomised users


def _resampled_sums(x: np.ndarray, resamples: int, rng: np.random.Generator) -> np.ndarray:
    n = x.shape[0]
    out = np.empty((resamples, x.shape[1]))
    for b in range(resamples):
        out[b] = np.bincount(rng.integers(0, n, n), minlength=n).astype(np.float64) @ x
    return out


def _summary(point: float, draws: np.ndarray, pcts: tuple) -> dict:
    return {"est": float(point), "lo": float(np.percentile(draws, pcts[0])), "hi": float(np.percentile(draws, pcts[1]))}


def boot_activation(tr: dict, s: np.ndarray, horizons: tuple, resamples: int, seed: int, pcts: tuple) -> dict:
    """Test A: resample users within arm, recompute first stage, revenue difference and rollout estimate together."""
    cols = [tr["rev"][:, :h].astype(np.float64) @ activation_weights(s, h) for h in horizons] + [tr["a"], tr["act3"].astype(np.float64)]
    x = np.column_stack(cols)
    arms = [x[tr["arm"] == j] for j in (0, 1)]
    point = [a.mean(axis=0) for a in arms]
    draws = [_resampled_sums(a, resamples, np.random.default_rng([seed, STREAM, 1, j])) / a.shape[0] for j, a in enumerate(arms)]
    ia, i3 = len(horizons), len(horizons) + 1
    tau, taus = point[1][ia] - point[0][ia], draws[1][:, ia] - draws[0][:, ia]
    out = {}
    for i, h in enumerate(horizons):
        out[str(h)] = _summary(0.01 * (point[1][i] - point[0][i]) / tau, 0.01 * (draws[1][:, i] - draws[0][:, i]) / taus, pcts)
    out["age3"] = _summary((point[1][i3] - point[0][i3]) / tau, (draws[1][:, i3] - draws[0][:, i3]) / taus, pcts)
    out["first_stage"] = _summary(tau, taus, pcts)
    return out


def boot_retention(tr: dict, mau_before: float, enter: np.ndarray, horizons: tuple, windows: dict, resamples: int, seed: int, pcts: tuple) -> dict:
    """Test C: the same, with monthly retention over each named window as the first stage."""
    act = tr["act"].astype(np.float64)
    prev = np.column_stack([np.ones(act.shape[0]), act[:, :-1]])
    kept = act * prev
    top = max(w[1] for w in windows.values())
    cols = [tr["rev"][:, :h].astype(np.float64) @ retention_weights(mau_before, enter, h) for h in horizons]
    x = np.column_stack(cols + [kept[:, :top], prev[:, :top]])
    arms = [x[tr["arm"] == j] for j in (0, 1)]
    point = [a.sum(axis=0) for a in arms]
    draws = [_resampled_sums(a, resamples, np.random.default_rng([seed, STREAM, 2, j])) for j, a in enumerate(arms)]
    ns = [a.shape[0] for a in arms]
    nh = len(horizons)

    def rate(arr, j, k):
        return arr[..., nh + k] / arr[..., nh + top + k]

    out = {}
    for name, w in windows.items():
        ks = range(w[0] - 1, w[1])
        tau = float(np.mean([rate(point[1], 1, k) - rate(point[0], 0, k) for k in ks]))
        taus = np.mean([rate(draws[1], 1, k) - rate(draws[0], 0, k) for k in ks], axis=0)
        block = {"first_stage": _summary(tau, taus, pcts)}
        for i, h in enumerate(horizons):
            d = point[1][i] / ns[1] - point[0][i] / ns[0]
            ds = draws[1][:, i] / ns[1] - draws[0][:, i] / ns[0]
            block[str(h)] = _summary(0.01 * d / tau, 0.01 * ds / taus, pcts)
        out[name] = block
    return out


# ------------------------------------------------------------------ the clocks


def holdout_clocks(ho: dict, start: int, months: int) -> dict:
    """By month since the change, z for the frozen pooled test and for the two corrected ones, all treated against control.

    pooled: cumulative monthly retention with user-months taken as independent, as first run.
    cluster: the same ratio of sums, its variance summed over users: sum (x_i - p e_i)^2 / (sum e_i)^2, x_i a user's retained
    months so far and e_i their eligible months so far.
    randomised: the share of the users randomised at the change who are active in that month; each user counts once.
    """
    s0 = start - 1
    pooled, cluster, randomised = [], [], []
    kn, kx = np.zeros(2), np.zeros(2)
    for k in range(months):
        mi = s0 + k
        kn = kn + ho["kpi_n"][mi]
        kx = kx + ho["kpi_x"][mi]
        p = kx / kn
        all_p = kx.sum() / kn.sum()
        pooled.append(float((p[1] - p[0]) / math.sqrt(all_p * (1 - all_p) * (1 / kn[1] + 1 / kn[0]))))
        var = (ho["xx"][mi] - 2 * p * ho["xe"][mi] + p * p * ho["ee"][mi]) / (kn * kn)
        cluster.append(float((p[1] - p[0]) / math.sqrt(var.sum())))
        nn, xn = ho["itt_n"][mi], ho["itt_x"][mi]
        q = xn / nn
        randomised.append(float((q[1] - q[0]) / math.sqrt((q * (1 - q) / nn).sum())))
    n, s, ss = ho["n"], ho["s"], ho["ss"]
    rev = []
    for k in range(months):
        mi = s0 + k
        mt, mc = s[mi][1] / n[mi][1], s[mi][0] / n[mi][0]
        vt, vc = (ss[mi][1] / n[mi][1] - mt * mt) / n[mi][1], (ss[mi][0] / n[mi][0] - mc * mc) / n[mi][0]
        rev.append(float((mt - mc) / math.sqrt(vt + vc)))
    return {"pooled": pooled, "cluster": cluster, "randomised": randomised, "revenue": rev}


# ------------------------------------------------------------------ which identities can fail


PLANTS = {"revenue_is_mau_times_arpu": "mau", "revenue_is_subscription_plus_ads": "rev_ads", "mau_is_new_retained_resurrected": "new",
          "retained_is_last_mau_times_retention": "retained", "subscription_is_payers_times_price": "paying_weeks",
          "margin_is_revenue_minus_costs": "cost_serving", "signups_are_the_channels": "signups_paid"}


def identity_faults(t: dict, identity_errors) -> dict:
    """Plant one fault in the table each identity reads and report whether the identity's check moves."""
    out = {}
    for name, col in PLANTS.items():
        broken = dict(t)
        broken["m"] = {k: v.copy() for k, v in t["m"].items()}
        broken["m"][col][30] += 1
        out[name] = bool(identity_errors(broken)[name] > 0.5)
    return out
