"""What a planner can compute: everything here reads only the planner tables a world hands over, never a user's intent, so
the same code runs on a world someone else wrote. Declared in DESIGN-kpitree.md sections 3 to 6.
"""
from __future__ import annotations

import math

import numpy as np

INDICATORS = ("activation", "week_one_days", "first_repeat", "profile", "paid_share", "signups", "placebo")


def arrays(t: dict) -> dict:
    out = dict(t)
    out["m"] = {k: np.array(v, dtype=float) for k, v in t["monthly"].items()}
    out["cohorts"] = np.array(t["cohorts"], dtype=float)
    out["flag3"] = np.array(t["flag3"], dtype=float)
    out["chan3"] = np.array(t["chan3"], dtype=float)
    out["days3"] = np.array(t["days3"], dtype=float)
    out["e2m"] = np.array(t["e2_by_month"], dtype=float)
    out["price"] = np.array(t["price"], dtype=float)
    return out


# ------------------------------------------------------------------ identities


def identity_errors(t: dict) -> dict:
    """Each identity's worst absolute error over the months. Bookkeeping: true by construction unless a table is wrong."""
    m = t["m"]
    mau, prev = m["mau"], np.r_[0.0, m["mau"][:-1]]
    ret = np.divide(m["retained"], prev, out=np.zeros_like(prev), where=prev > 0)
    return {
        "revenue_is_mau_times_arpu": float(np.max(np.abs(m["revenue"] - mau * (m["revenue"] / mau)))),
        "revenue_is_subscription_plus_ads": float(np.max(np.abs(m["revenue"] - m["rev_sub"] - m["rev_ads"]))),
        "mau_is_new_retained_resurrected": float(np.max(np.abs(mau - m["new"] - m["retained"] - m["resurrected"]))),
        "retained_is_last_mau_times_retention": float(np.max(np.abs(m["retained"] - prev * ret))),
        "subscription_is_payers_times_price": float(np.max(np.abs(m["rev_sub"] - m["paying_weeks"] / 4 * t["price"]))),
        "margin_is_revenue_minus_costs": float(np.max(np.abs(m["margin"] - m["revenue"] + m["cost_fees"] + m["cost_serving"] + m["cost_acq"]))),
        "signups_are_the_channels": float(np.max(np.abs(m["signups"] - m["signups_organic"] - m["signups_paid"] - m["signups_referral"]))),
    }


# ------------------------------------------------------------------ indicators on rolling origins


def indicator_series(t: dict, seed: int, placebo_phi: float, placebo_sigma: float) -> dict:
    m = t["m"]
    s = m["signups"]
    n = len(s)
    rng = np.random.default_rng([seed, 77])
    z = np.zeros(n)
    x = rng.normal(0, placebo_sigma / math.sqrt(1 - placebo_phi ** 2))
    for i in range(n):
        z[i] = x
        x = placebo_phi * x + rng.normal(0, placebo_sigma)
    return {"activation": m["activated"] / s, "week_one_days": m["week_one_days"] / s, "first_repeat": m["first_repeat"] / s,
            "profile": m["profile"] / s, "paid_share": m["signups_paid"] / s, "signups": s.copy(), "placebo": np.exp(z)}


def cohort_targets(t: dict) -> dict:
    c = t["cohorts"]
    n = c[:, 0, 0, 0] + c[:, 1, 0, 0]
    return {"third_month_retention": (c[:, 0, 3, 1] + c[:, 1, 3, 1]) / n,
            "revenue_per_signup_six_months": (c[:, 0, :6, 2].sum(axis=1) + c[:, 1, :6, 2].sum(axis=1)) / n}


def _project(v: np.ndarray, c: int, lag: int) -> float:
    """Last year's same value times the growth of the latest three known values over the same three a year earlier."""
    return float(v[c - 12] * v[c - lag - 2:c - lag + 1].mean() / v[c - lag - 14:c - lag - 11].mean())


def test_cohort(y: np.ndarray, x: np.ndarray, lead: int, delay: int, min_train: int) -> dict:
    """y of cohort c is known `lead` months after c; the indicator of cohort c is known `delay` months after c."""
    lag = lead - delay
    first = lag + 14
    n = len(y)
    zs, bs = {}, {}
    for c in range(first, n):
        bs[c] = _project(y, c, lag)
        zs[c] = math.log(x[c]) - math.log(_project(x, c, lag))
    ys, base_err, model_err, sl, beta = [], [], [], [], float("nan")
    for c in range(first, n - lead):  # a cohort whose target falls past the world's end cannot be scored
        known = [k for k in range(first, c + 1) if k + lead <= c + delay]
        if len(known) < min_train:
            continue
        a = np.array([zs[k] for k in known])
        b = np.array([math.log(y[k]) - math.log(bs[k]) for k in known])
        den = float((a * a).sum())
        beta = float((a * b).sum() / den) if den > 0 else 0.0
        pred = bs[c] * math.exp(beta * zs[c])
        base_err.append(abs(bs[c] - y[c]) / y[c] * 100)
        model_err.append(abs(pred - y[c]) / y[c] * 100)
        sl.append(beta)
        ys.append(c)
    return {"cohorts": ys, "base": np.array(base_err), "model": np.array(model_err), "beta": beta, "slopes": sl}


def test_revenue(R: np.ndarray, x: np.ndarray, h: int, delay: int, min_train: int) -> dict:
    n = len(R)
    first = 14 + delay
    zs, bs = {}, {}
    for t in range(first, n - h):
        bs[t] = float(R[t + h - 12] * R[t - 2:t + 1].sum() / R[t - 14:t - 11].sum())
        e = t - delay
        zs[t] = math.log(x[e - 2:e + 1].mean()) - math.log(x[e - 14:e - 11].mean())
    origins, base_err, model_err, sl, beta = [], [], [], [], float("nan")
    for t in range(first, n - h):
        known = [k for k in range(first, t) if k + h <= t]
        if len(known) < min_train:
            continue
        a = np.array([zs[k] for k in known])
        b = np.array([math.log(R[k + h]) - math.log(bs[k]) for k in known])
        den = float((a * a).sum())
        beta = float((a * b).sum() / den) if den > 0 else 0.0
        pred = bs[t] * math.exp(beta * zs[t])
        base_err.append(abs(bs[t] - R[t + h]) / R[t + h] * 100)
        model_err.append(abs(pred - R[t + h]) / R[t + h] * 100)
        sl.append(beta)
        origins.append(t)
    return {"origins": origins, "base": np.array(base_err), "model": np.array(model_err), "beta": beta, "slopes": sl}


def block_interval(model: np.ndarray, base: np.ndarray, block: int, resamples: int, seed: int) -> tuple:
    d = model - base
    n = len(d)
    rng = np.random.default_rng(seed)
    k = int(np.ceil(n / block))
    starts = rng.integers(0, n - block + 1, size=(resamples, k))
    idx = (starts[:, :, None] + np.arange(block)).reshape(resamples, -1)[:, :n]
    means = d[idx].mean(axis=1)
    return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5))


def indicator_cells(t: dict, seed: int, pro: dict, with_intervals: bool) -> dict:
    """Every indicator against every target: errors, slope and, for the main world, the paired interval."""
    ip = pro["indicators"]
    xs = indicator_series(t, seed, ip["placebo_phi"], ip["placebo_sigma"])
    ys = cohort_targets(t)
    R = t["m"]["revenue"]
    boot = pro["bootstrap"]
    out = {}
    mt = int(ip["min_training"])
    k = 0
    for name in ip["names"]:
        delay = 1 if name == "first_repeat" else 0
        x = xs[name]
        cells = {}
        for tname, lead in ip["cohort_targets"].items():
            r = test_cohort(ys[tname], x, int(lead), delay, mt)
            cells[tname] = _cell(r, with_intervals, boot, k, float(np.mean(ys[tname]) / np.mean(x)))
            k += 1
        for h in ip["revenue_horizons"]:
            r = test_revenue(R, x, int(h), delay, mt)
            cells[f"revenue_h{h}"] = _cell(r, with_intervals, boot, k, float(np.mean(R) / np.mean(x)))
            k += 1
        out[name] = cells
    return out


def _cell(r: dict, with_intervals: bool, boot: dict, k: int, scale: float) -> dict:
    base, model = r["base"].mean(), r["model"].mean()
    cell = {"n": len(r["base"]), "base_mape": float(base), "model_mape": float(model), "diff": float(model - base),
            "beats": bool(model < base), "beta": r["beta"], "size_per_unit": float(r["beta"] * scale),
            "share_positive_slopes": float(np.mean(np.array(r["slopes"]) > 0))}
    if with_intervals:
        lo, hi = block_interval(r["model"], r["base"], int(boot["block"]), int(boot["resamples"]), int(boot["seed"]) + k)
        cell.update(lo=lo, hi=hi, wins=int((r["model"] < r["base"]).sum()))
    return cell


# ------------------------------------------------------------------ association against cause


def _first_stage(test: dict) -> tuple:
    c, g = test["control"], test["treated"]
    pc, pt = c["a"] / c["n"], g["a"] / g["n"]
    return pt - pc, math.sqrt(pt * (1 - pt) / g["n"] + pc * (1 - pc) / c["n"])


def _rate_diff_se(xt, nt, xc, nc):
    pt, pc = xt / nt, xc / nc
    return pt - pc, math.sqrt(pt * (1 - pt) / nt + pc * (1 - pc) / nc)


def association_and_cause(t: dict) -> dict:
    first_test = int(t["e1_first_month"]) - 1
    f = t["flag3"][:first_test]
    out = {}
    for j, name in enumerate(("activated", "profile", "first_repeat")):
        v = f[:, j]
        one, zero = v[:, 1, 1].sum() / v[:, 1, 0].sum(), v[:, 0, 1].sum() / v[:, 0, 0].sum()
        out[name] = {"association_points": float((one - zero) * 100), "with": float(one * 100), "without": float(zero * 100)}
    for key, name in (("e1", "activated"), ("e3", "profile")):
        test = t["tests"][key]
        tau, se_tau = _first_stage(test)
        ba = np.array(test["by_age"], dtype=float)
        nt, nc = test["treated"]["n"], test["control"]["n"]
        d, se_d = _rate_diff_se(ba[1, 3, 0], nt, ba[0, 3, 0], nc)
        eff = d / tau
        se = math.sqrt((se_d / tau) ** 2 + (d * se_tau / tau ** 2) ** 2)
        out[name].update(test_first_stage_points=float(tau * 100), test_itt_points=float(d * 100), test_itt_lo=float((d - 1.96 * se_d) * 100),
                         test_itt_hi=float((d + 1.96 * se_d) * 100), test_effect_per_point=float(eff), test_lo=float(eff - 1.96 * se),
                         test_hi=float(eff + 1.96 * se), n_arms=[int(nc), int(nt)])
    d = t["days3"]
    days = np.arange(d.shape[0])[1:]
    rate = d[1:, 1] / np.maximum(d[1:, 0], 1)
    w = d[1:, 0]
    mx = float((days * w).sum() / w.sum())
    my = float((rate * w).sum() / w.sum())
    slope = float((w * (days - mx) * (rate - my)).sum() / (w * (days - mx) ** 2).sum())
    out["week_one_days"] = {"association_points_per_day": slope * 100, "n_among_activated": int(w.sum())}
    return out


# ------------------------------------------------------------------ what a point is worth


def _ret_lift(t: dict) -> tuple:
    e2m, c, g = t["e2m"], t["tests"]["e2"]["control"], t["tests"]["e2"]["treated"]
    diffs, var = [], 0.0
    for k in range(3):
        nt = g["n"] if k == 0 else e2m[1, k - 1, 0]
        nc = c["n"] if k == 0 else e2m[0, k - 1, 0]
        d, se = _rate_diff_se(e2m[1, k, 2], nt, e2m[0, k, 2], nc)
        diffs.append(d)
        var += se * se
    return float(np.mean(diffs)), math.sqrt(var) / 3


def _ratio_rel_se(test: dict, tau: float, se_tau: float, h: int) -> tuple:
    r, rr = f"r{h}", f"r{h}r{h}"
    c, g = test["control"], test["treated"]
    mt, mc = g[r] / g["n"], c[r] / c["n"]
    vt = max(g[rr] / g["n"] - mt * mt, 0.0) / g["n"]
    vc = max(c[rr] / c["n"] - mc * mc, 0.0) / c["n"]
    d = mt - mc
    ratio = d / tau
    se = math.sqrt((math.sqrt(vt + vc) / tau) ** 2 + (d * se_tau / tau ** 2) ** 2)
    return ratio, se, (abs(se / ratio) if ratio != 0 else float("inf"))


def value_estimates(t: dict, start: int, months: int, use_tests: bool) -> dict:
    """Monthly revenue change of one point of each lever, over `months` from month `start` (1-based), on the base run's tables."""
    m = t["m"]
    s0 = start - 1
    months = min(months, len(m["revenue"]) - s0)
    S = m["signups"][s0:s0 + months]
    c = t["cohorts"]
    # arithmetic, activation: revenue per user by age, activated minus not, over the 12 calendar months before the change
    delta = np.zeros(24)
    for a in range(24):
        r1 = n1 = r0 = n0 = 0.0
        for mo in range(max(0, s0 - 12), s0):
            co = mo - a
            if co < 0:
                continue
            r1 += c[co, 1, a, 2]
            n1 += c[co, 1, 0, 0]
            r0 += c[co, 0, a, 2]
            n0 += c[co, 0, 0, 0]
        if n1 > 0 and n0 > 0:
            delta[a] = r1 / n1 - r0 / n0
    arith_act = np.zeros(months)
    for k in range(months):
        for j in range(k + 1):
            arith_act[k] += S[j] * 0.01 * delta[k - j]
    # arithmetic, retention: extra users rolled forward at the month's retention plus a point, times the month's ARPU
    mau = m["mau"]
    arith_ret = np.zeros(months)
    dm = 0.0
    for k in range(months):
        mo = s0 + k
        ret = m["retained"][mo] / mau[mo - 1]
        dm = dm * (ret + 0.01) + 0.01 * mau[mo - 1]
        arith_ret[k] = dm * m["revenue"][mo] / mau[mo]
    out = {"arith_activation": arith_act, "arith_retention": arith_ret, "delta_by_age": delta}
    if not use_tests:
        return out
    # scaled from test A
    e1 = t["tests"]["e1"]
    tau_a, se_a = _first_stage(e1)
    by = np.array(e1["by_age"], dtype=float)
    d_a = by[1, :, 1] / e1["treated"]["n"] - by[0, :, 1] / e1["control"]["n"]
    test_act = np.zeros(months)
    for k in range(months):
        for j in range(k + 1):
            test_act[k] += S[j] * (0.01 / tau_a) * d_a[k - j]
    # scaled from test C
    e2 = t["tests"]["e2"]
    tau_r, se_r = _ret_lift(t)
    e2m = 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]
    test_ret = np.zeros(months)
    for k in range(months):
        v = mau[s0 - 1] * d_r[k]
        for j in range(k):
            v += enter[j] * d_r[k - j - 1]
        test_ret[k] = v * 0.01 / tau_r
    rel = {}
    for h in (12, 24):
        rel[f"activation_{h}"] = _ratio_rel_se(e1, tau_a, se_a, h)[2]
        rel[f"retention_{h}"] = _ratio_rel_se(e2, tau_r, se_r, h)[2]
    out.update(test_activation=test_act, test_retention=test_ret, rel_se=rel, tau_activation=tau_a, tau_retention=tau_r,
               se_tau_activation=se_a, se_tau_retention=se_r)
    return out


def interval(value: float, rel_se: float) -> tuple:
    return value - 1.96 * rel_se * abs(value), value + 1.96 * rel_se * abs(value)


def noise_band(R: np.ndarray, start: int, months: int, q: float) -> dict:
    """The naive baseline's one-month-ahead percent errors over the months before the change, and their absolute quantile."""
    s0 = start - 1
    errs = []
    for tgt in range(s0 - months, s0):
        o = tgt - 1
        if o - 14 < 0:
            continue
        b = R[tgt - 12] * R[o - 2:o + 1].sum() / R[o - 14:o - 11].sum()
        errs.append(abs(R[tgt] - b) / R[tgt] * 100)
    return {"half_width_pct": float(np.quantile(errs, q)), "n": len(errs), "errors": errs}


def holdout_z(ho: dict, start: int, months: int) -> dict:
    """z on the cumulative KPI and on cumulative revenue per user, treated (arm 1) against control, by month since the change."""
    s0 = start - 1
    zk, zr = [], []
    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]
        pt, pc = kx[1] / kn[1], kx[0] / kn[0]
        p = (kx[1] + kx[0]) / (kn[1] + kn[0])
        zk.append(float((pt - pc) / math.sqrt(p * (1 - p) * (1 / kn[1] + 1 / kn[0]))))
        n, s, ss = ho["n"][mi], ho["s"][mi], ho["ss"][mi]
        mt, mc = s[1] / n[1], s[0] / n[0]
        vt, vc = (ss[1] / n[1] - mt * mt) / n[1], (ss[0] / n[0] - mc * mc) / n[0]
        zr.append(float((mt - mc) / math.sqrt(vt + vc)))
    return {"kpi": zk, "revenue": zr}
