"""The synthetic home-workout app of the KPI tree part: every user, week by week, in one seeded world.

Everything a planner would see leaves this file as tables (`World.tables`). The planner's code in revfc/kpitree.py reads
only those tables, never a user's intent, so the same code can run on a world someone else wrote. Levers re-run the world
from a snapshot with the same random numbers (common random numbers), so a lever's difference is its effect, not a new
draw of chance.

A month is exactly four weeks and a year twelve months, so no month is longer than another. Month 1 is a January.
"""
from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path

import numpy as np
from scipy.stats import binom, poisson

ROOT = Path(__file__).resolve().parents[1]
W = 4  # weeks in a month
CH = ("organic", "paid", "referral")


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


def expit(x):
    return 1.0 / (1.0 + np.exp(-x))


def ar1(rng, n, phi, sigma):
    out = np.zeros(n)
    x = rng.normal(0, sigma / np.sqrt(max(1e-9, 1 - phi * phi)))
    for i in range(n):
        out[i] = x
        x = phi * x + rng.normal(0, sigma)
    return out


@dataclass
class Lever:
    """A change from `start` (month, 1-based) on. Shifts are on the log-odds scale, multipliers on the level."""
    start: int | None = None
    act: float = 0.0        # log-odds of activation, sign-ups from `start`
    lapse: float = 0.0      # log-odds of lapsing in a week, every live user (positive means fewer lapse)
    rep: float = 0.0        # log-odds of a first repeat, sign-ups from `start`
    ret: float = 0.0        # log-odds of a lapsed user returning in a week
    conv: float = 0.0       # log-odds of a free active user starting to pay in a week
    cancel: float = 0.0     # log-odds of a payer cancelling in a week (positive means fewer cancel)
    signup: float = 1.0     # organic and paid sign-ups, multiplier
    price: float = 1.0      # subscription price, multiplier
    ads: float = 1.0        # ad revenue per free active week, multiplier
    holdout: bool = False   # apply to a random half and report by arm


class World:
    def __init__(self, pro: dict, seed: int):
        self.pro, self.seed = pro, seed
        w = pro["world"]
        self.w = w
        self.months = int(w["months"])
        self.T = self.months * W
        rng = np.random.default_rng([seed, 1])
        m = np.arange(self.months)
        moy = m % 12
        self.moy = moy
        s_sign = np.array(w["signup_season"])[moy]
        n_o = ar1(rng, self.months, w["organic_noise_phi"], w["organic_noise_sigma"])
        self.lam_org = w["organic_per_week"] * (1 + w["organic_growth_monthly"]) ** m * s_sign * np.exp(n_o)
        budget = np.zeros(self.months)
        for i in range(0, self.months, int(w["budget_step_months"])):
            budget[i:i + int(w["budget_step_months"])] = rng.uniform(w["budget_low"], w["budget_high"])
        self.lam_paid = w["paid_per_week"] * budget * s_sign
        self.q = ar1(rng, self.months, w["quality_phi"], w["quality_sigma"])
        self.q_season = np.array(w["quality_season"])[moy]
        self.macro_act = ar1(rng, self.months, w["macro_active_phi"], w["macro_active_sigma"])
        self.macro_lap = ar1(rng, self.months, w["macro_lapse_phi"], w["macro_lapse_sigma"])
        self.macro_lap = self.macro_lap + (rng.random(self.months) < w["outage_prob"]) * w["outage_size"]
        self.ads_noise = np.exp(ar1(rng, self.months, w["ads_noise_phi"], w["ads_noise_sigma"]))
        self.ads_season = np.array(w["ads_season"])[moy]
        self.act_season = np.array(w["active_season"])[moy]
        self.price = np.where(m + 1 >= w["price_step_month"], w["price_after"], w["price_before"])
        # The pool: pre-drawn slots, so a lever that adds sign-ups fills more slots and never moves anyone else's numbers.
        rng_pool = np.random.default_rng([seed, 2])
        self.u_count = rng_pool.random((self.T, 3))
        caps = np.zeros((self.T, 3), dtype=np.int64)
        for t in range(self.T):
            mi = t // W
            lo, lp = self.lam_org[mi], self.lam_paid[mi]
            caps[t, 0] = int(lo * w["slack"] + 6 * np.sqrt(lo)) + 1
            caps[t, 1] = int(lp * w["slack"] + 6 * np.sqrt(lp)) + 1
            caps[t, 2] = int(w["referral_cap_per_week"])
        self.caps = caps
        self.slot0 = np.zeros((self.T, 3), dtype=np.int64)
        pos = 0
        for t in range(self.T):
            for c in range(3):
                self.slot0[t, c] = pos
                pos += caps[t, c]
        self.N = pos
        self.pool_end = np.array([self.slot0[t, 2] + caps[t, 2] for t in range(self.T)], dtype=np.int64)
        self.sweek = np.zeros(self.N, dtype=np.int16)
        self.chan = np.zeros(self.N, dtype=np.int8)
        for t in range(self.T):
            for c in range(3):
                a, b = self.slot0[t, c], self.slot0[t, c] + caps[t, c]
                self.sweek[a:b], self.chan[a:b] = t, c
        self.cohort = (self.sweek // W).astype(np.int16)  # 0-based month
        mu = np.array([w["intent_organic"], w["intent_paid"], w["intent_referral"]], dtype=np.float32)
        self.theta = (mu[self.chan] + (self.q_season[self.cohort] + self.q[self.cohort]).astype(np.float32)
                      + rng_pool.standard_normal(self.N, dtype=np.float32))
        self.uA, self.uP, self.uH, self.uD = (rng_pool.random(self.N, dtype=np.float32) for _ in range(4))
        self.uHold, self.uE1, self.uE3, self.uE2 = (rng_pool.random(self.N, dtype=np.float32) for _ in range(4))
        self.a_static = w["act_base"] + w["act_intent"] * self.theta
        self.p_ret = expit(w["return_base"] + w["return_intent"] * self.theta).astype(np.float32)
        self.snapshots: dict = {}
        self.tables = None

    # ------------------------------------------------------------------ one arm

    def fresh_state(self) -> dict:
        N, M = self.N, self.months
        st = {k: np.zeros(N, dtype=bool) for k in ("exists", "live", "U", "A", "H", "P", "paying", "active_m", "active_prev", "ever",
                                                   "e1_pop", "e1_t", "e3_t", "e2_pop", "e2_t", "ho_pop", "ho_t")}
        st["rev_m"] = np.zeros(N, dtype=np.float32)
        st["cum12"] = np.zeros(N, dtype=np.float32)
        st["cum24"] = np.zeros(N, dtype=np.float32)
        st["ho_cum"] = np.zeros(N, dtype=np.float32)
        st["ref_lam"] = 0.0
        keys = ["signups_organic", "signups_paid", "signups_referral", "signups", "activated", "profile", "week_one_days",
                "first_repeat", "mau", "new", "retained", "resurrected", "paying_weeks", "active_weeks", "free_active_weeks",
                "rev_sub", "rev_ads", "cost_fees", "cost_serving", "cost_acq", "revenue", "margin"]
        st["monthly"] = {k: np.zeros(M) for k in keys}
        st["cohorts"] = np.zeros((M, 2, 24, 3))        # cohort month, activated flag, age month: n, active users, revenue
        st["flag3"] = np.zeros((M, 3, 2, 2))           # cohort, flag (activated, profile, first repeat), value: n, active at age 3
        st["chan3"] = np.zeros((M, 3, 3))              # cohort, channel: n, activated, active at age 3
        st["days3"] = np.zeros((8, 2))                 # week-one active days 0 to 7, cohorts at least 3 months old: n, active at age 3
        st["e1"] = np.zeros((2, 24, 2))                # arm, age month: active users, revenue
        st["e3"] = np.zeros((2, 24, 2))
        st["e2"] = np.zeros((2, 24, 3))                # arm, month since start: active users, revenue, retained from the month before
        st["ho"] = {"n": np.zeros((M, 2)), "s": np.zeros((M, 2)), "ss": np.zeros((M, 2)),
                    "kpi_n": np.zeros((M, 2)), "kpi_x": np.zeros((M, 2))}
        return st

    def run(self, lever: Lever | None = None, snapshot_at: tuple = (), stop: int | None = None) -> dict:
        """Run the world. With a lever, resume from the base run's snapshot at the lever's start month."""
        lever = lever or Lever()
        w, N = self.w, self.N
        if lever.start is not None:
            st = _copy_state(self.snapshots[lever.start])
            first_month = lever.start - 1
        else:
            st = self.fresh_state()
            first_month = 0
        mly = st["monthly"]
        e1a, e1b = int(w["e1_first_month"]) - 1, int(w["e1_last_month"]) - 1
        e2s = int(w["e2_start_month"]) - 1
        last_month = self.months if stop is None else min(stop, self.months)
        for mi in range(first_month, last_month):
            if mi + 1 in snapshot_at and lever.start is None:
                self.snapshots[mi + 1] = _copy_state(st)
            on = lever.start is not None and mi + 1 >= lever.start
            if on and lever.holdout and mi + 1 == lever.start and lever.lapse != 0.0:
                ix = np.flatnonzero(st["active_prev"])
                st["ho_pop"][ix] = True
                st["ho_t"][ix] = self.uHold[ix] < 0.5
            if mi == e2s:
                ix = np.flatnonzero(st["active_prev"])
                pick = self.uE2[ix] < w["e2_sample"]
                ix = ix[pick]
                st["e2_pop"][ix] = True
                st["e2_t"][ix] = self.uE2[ix] < w["e2_sample"] / 2
            price = self.price[mi] * (lever.price if on else 1.0)
            ad_rate = float(w["ads_per_free_active_week"] * self.ads_season[mi] * self.ads_noise[mi]) * (lever.ads if on else 1.0)
            sa = float(self.act_season[mi] + self.macro_act[mi])
            ml = float(self.macro_lap[mi])
            for t in range(mi * W, (mi + 1) * W):
                rng = np.random.default_rng([self.seed, 1000, t])
                n_now = int(self.pool_end[t])
                u = rng.random((4, n_now), dtype=np.float32)
                # sign-ups
                lams = [self.lam_org[mi] * (lever.signup if on else 1.0), self.lam_paid[mi] * (lever.signup if on else 1.0), st["ref_lam"]]
                sign_idx = []
                for c in range(3):
                    k = int(poisson.ppf(self.u_count[t, c], max(lams[c], 1e-9))) if lams[c] > 0 else 0
                    k = min(k, int(self.caps[t, c]))
                    a = int(self.slot0[t, c])
                    sign_idx.append(np.arange(a, a + k))
                    mly["signups_" + CH[c]][mi] += k
                ix = np.concatenate(sign_idx)
                mly["signups"][mi] += len(ix)
                th = self.theta[ix]
                st["exists"][ix] = True
                st["live"][ix] = True
                acts = self.a_static[ix] + (lever.act * (self.uHold[ix] < 0.5 if lever.holdout else 1.0) if on else 0.0)
                prof = w["profile_base"] + w["profile_intent"] * th
                if e1a <= mi <= e1b:
                    st["e1_pop"][ix] = True
                    st["e1_t"][ix] = self.uE1[ix] < 0.5
                    st["e3_t"][ix] = self.uE3[ix] < 0.5
                    acts = acts + st["e1_t"][ix] * w["e1_act_logit"]
                    prof = prof + st["e3_t"][ix] * w["e3_profile_logit"]
                A = self.uA[ix] < expit(acts)
                P = self.uP[ix] < expit(prof)
                H = A & (self.uH[ix] < expit(w["repeat_base"] + w["repeat_intent"] * th + (lever.rep if on else 0.0)))
                D = np.where(A, 1 + binom.ppf(self.uD[ix], 6, expit(w["days_base"] + w["days_intent"] * th)), 0).astype(int)
                st["A"][ix], st["P"][ix], st["H"][ix] = A, P, H
                st["U"][ix] = A
                mly["activated"][mi] += A.sum()
                mly["profile"][mi] += P.sum()
                mly["first_repeat"][mi] += H.sum()
                mly["week_one_days"][mi] += D.sum()
                np.add.at(st["cohorts"][..., 0], (self.cohort[ix], A.astype(int), 0), 1.0)
                for fl, arr in enumerate((A, P, H)):
                    np.add.at(st["flag3"][..., 0], (self.cohort[ix], fl, arr.astype(int)), 1.0)
                np.add.at(st["chan3"][..., 0], (self.cohort[ix], self.chan[ix]), 1.0)
                np.add.at(st["chan3"][..., 1], (self.cohort[ix], self.chan[ix]), A.astype(float))
                st.setdefault("D", np.zeros(N, dtype=np.int8))[ix] = D
                if on and lever.holdout and lever.act != 0.0:
                    st["ho_pop"][ix] = True
                    st["ho_t"][ix] = self.uHold[ix] < 0.5
                    arm = st["ho_t"][ix].astype(int)
                    np.add.at(st["ho"]["kpi_n"][mi], arm, 1.0)
                    np.add.at(st["ho"]["kpi_x"][mi], arm, A.astype(float))
                # the live users act
                li = np.flatnonzero(st["live"][:n_now])
                age = t - self.sweek[li].astype(np.int32)
                thl = self.theta[li]
                Ul = st["U"][li]
                x = w["active_base"] + w["active_started"] * Ul + w["active_intent"] * thl + sa
                act = u[0, li] < expit(x)
                z = age == 0
                act[z] = st["A"][li][z]
                o = (age == 1) & st["A"][li]
                act[o] = st["H"][li][o]
                ai = li[act]
                st["U"][ai] = True
                st["active_m"][ai] = True
                # money
                pay = np.flatnonzero(st["paying"][:n_now])
                st["rev_m"][pay] += price / W
                free_ai = ai[~st["paying"][ai]]
                st["rev_m"][free_ai] += ad_rate
                mly["paying_weeks"][mi] += len(pay)
                mly["active_weeks"][mi] += len(ai)
                mly["free_active_weeks"][mi] += len(free_ai)
                mly["rev_sub"][mi] += len(pay) * price / W
                mly["rev_ads"][mi] += len(free_ai) * ad_rate
                # free active users may start paying; payers may cancel
                cx = w["convert_base"] + w["convert_intent"] * self.theta[free_ai] + (lever.conv if on else 0.0)
                st["paying"][free_ai[u[1, free_ai] < expit(cx)]] = True
                lv = st["live"][pay]
                pc = np.where(lv, expit(w["cancel_live"] - w["cancel_intent"] * self.theta[pay] - (lever.cancel if on else 0.0)),
                              expit(w["cancel_lapsed"] - (lever.cancel if on else 0.0)))
                st["paying"][pay[u[2, pay] < pc]] = False
                # lapses and returns
                lapsed = np.flatnonzero(st["exists"][:n_now] & ~st["live"][:n_now])
                hz = (w["lapse_base"] + w["lapse_young"] * np.exp(-age / w["lapse_young_weeks"]) - w["lapse_intent"] * thl
                      - w["lapse_started"] * st["U"][li] - w["lapse_repeat"] * st["H"][li] + ml)
                if mi >= e2s:
                    hz = hz - st["e2_t"][li] * w["e2_lapse_logit"]
                if on and lever.lapse != 0.0:
                    hz = hz - (lever.lapse * st["ho_t"][li] if lever.holdout else lever.lapse)
                gone = li[u[3, li] < expit(hz)]
                if on and lever.ret != 0.0:
                    back = lapsed[u[3, lapsed] < expit(w["return_base"] + w["return_intent"] * self.theta[lapsed] + lever.ret)]
                else:
                    back = lapsed[u[3, lapsed] < self.p_ret[lapsed]]
                st["live"][gone] = False
                st["live"][back] = True
            # month end
            n_now = int(self.pool_end[(mi + 1) * W - 1])
            am, ap, ev = st["active_m"][:n_now], st["active_prev"][:n_now], st["ever"][:n_now]
            mly["mau"][mi] = am.sum()
            mly["retained"][mi] = (am & ap).sum()
            mly["new"][mi] = (am & ~ev).sum()
            mly["resurrected"][mi] = (am & ~ap & ev).sum()
            rm = st["rev_m"][:n_now]
            mly["cost_fees"][mi] = mly["rev_sub"][mi] * w["payment_fee"]
            mly["cost_serving"][mi] = mly["active_weeks"][mi] * w["serving_per_active_week"]
            mly["cost_acq"][mi] = mly["signups_paid"][mi] * w["cost_per_paid_signup"]
            mly["revenue"][mi] = mly["rev_sub"][mi] + mly["rev_ads"][mi]
            mly["margin"][mi] = mly["revenue"][mi] - mly["cost_fees"][mi] - mly["cost_serving"][mi] - mly["cost_acq"][mi]
            # cohort table: last 24 cohorts, by activated flag
            ages = mi - self.cohort[:n_now].astype(np.int32)
            ix = np.flatnonzero(st["exists"][:n_now] & (ages < 24) & (am | (rm > 0)))
            co, fl, ag = self.cohort[ix], st["A"][ix].astype(int), ages[ix]
            np.add.at(st["cohorts"][..., 1], (co, fl, ag), am[ix].astype(float))
            np.add.at(st["cohorts"][..., 2], (co, fl, ag), rm[ix].astype(float))
            # age-3 tables
            if mi >= 3:
                ix = np.flatnonzero(st["exists"][:n_now] & (ages == 3))
                a3 = am[ix].astype(float)
                co = self.cohort[ix]
                for f, name in enumerate(("A", "P", "H")):
                    np.add.at(st["flag3"][..., 1], (co, f, st[name][ix].astype(int)), a3)
                np.add.at(st["chan3"][..., 2], (co, self.chan[ix]), a3)
                d = st["D"][ix].astype(int)
                np.add.at(st["days3"][:, 0], d, 1.0)
                np.add.at(st["days3"][:, 1], d, a3)
            # experiments
            for name, flag in (("e1", "e1_t"), ("e3", "e3_t")):
                ix = np.flatnonzero(st["e1_pop"][:n_now] & st["exists"][:n_now] & (ages < 24))
                arm = st[flag][ix].astype(int)
                np.add.at(st[name][..., 0], (arm, ages[ix]), am[ix].astype(float))
                np.add.at(st[name][..., 1], (arm, ages[ix]), rm[ix].astype(float))
            ix = np.flatnonzero(st["e1_pop"][:n_now] & st["exists"][:n_now])
            st["cum12"][ix[ages[ix] < 12]] += rm[ix[ages[ix] < 12]]
            st["cum24"][ix[ages[ix] < 24]] += rm[ix[ages[ix] < 24]]
            if mi >= e2s:
                k = mi - e2s
                ix = np.flatnonzero(st["e2_pop"][:n_now])
                arm = st["e2_t"][ix].astype(int)
                if k < 24:
                    np.add.at(st["e2"][..., 0], (arm, np.full(len(ix), k)), am[ix].astype(float))
                    np.add.at(st["e2"][..., 1], (arm, np.full(len(ix), k)), rm[ix].astype(float))
                    np.add.at(st["e2"][..., 2], (arm, np.full(len(ix), k)), (am[ix] & ap[ix]).astype(float))
                    if k < 12:
                        st["cum12"][ix] += rm[ix]
                    st["cum24"][ix] += rm[ix]
            if on and lever.holdout:
                ix = np.flatnonzero(st["ho_pop"][:n_now])
                arm = st["ho_t"][ix].astype(int)
                st["ho_cum"][ix] += rm[ix]
                v = st["ho_cum"][ix].astype(np.float64)
                np.add.at(st["ho"]["n"][mi], arm, 1.0)
                np.add.at(st["ho"]["s"][mi], arm, v)
                np.add.at(st["ho"]["ss"][mi], arm, v * v)
                if lever.lapse != 0.0:
                    ib = np.flatnonzero(ap & st["ho_pop"][:n_now])
                    armb = st["ho_t"][ib].astype(int)
                    np.add.at(st["ho"]["kpi_n"][mi], armb, 1.0)
                    np.add.at(st["ho"]["kpi_x"][mi], armb, am[ib].astype(float))
            # roll over
            st["ever"][:n_now] |= am
            st["active_prev"][:n_now] = am
            st["active_m"][:n_now] = False
            st["rev_m"][:n_now] = 0.0
            st["ref_lam"] = w["referral_per_mau_month"] * mly["mau"][mi] / W
        return st

    # ------------------------------------------------------------------ what a planner sees

    def planner_tables(self, st: dict) -> dict:
        """The tables a planner has: monthly lines, cohorts by age and by activated flag, flags at age 3, and the three tests."""
        w = self.w
        e1 = st["e1_pop"]
        e1_ix = np.flatnonzero(e1 & st["exists"])
        e2_ix = np.flatnonzero(st["e2_pop"])
        tests = {}
        for name, ix, flag, first in (("e1", e1_ix, st["e1_t"], st["A"]), ("e3", e1_ix, st["e3_t"], st["P"])):
            arm = flag[ix].astype(int)
            tests[name] = _test_summary(arm, first[ix].astype(float), st["cum12"][ix].astype(float), st["cum24"][ix].astype(float))
            tests[name]["by_age"] = st[name].tolist()
        arm = st["e2_t"][e2_ix].astype(int)
        tests["e2"] = _test_summary(arm, np.zeros(len(e2_ix)), st["cum12"][e2_ix].astype(float), st["cum24"][e2_ix].astype(float))
        return {"monthly": {k: v.tolist() for k, v in st["monthly"].items()},
                "cohorts": st["cohorts"].tolist(), "flag3": st["flag3"].tolist(), "chan3": st["chan3"].tolist(),
                "days3": st["days3"].tolist(), "tests": tests, "e2_by_month": st["e2"].tolist(),
                "price": self.price.tolist(), "e1_first_month": int(w["e1_first_month"]), "e1_last_month": int(w["e1_last_month"]),
                "e2_start_month": int(w["e2_start_month"]), "months": self.months}


def _test_summary(arm, a, r12, r24) -> dict:
    out = {}
    for j, nm in ((0, "control"), (1, "treated")):
        m = arm == j
        out[nm] = {"n": int(m.sum()), "a": float(a[m].sum()), "r12": float(r12[m].sum()), "r12r12": float((r12[m] ** 2).sum()),
                   "r24": float(r24[m].sum()), "r24r24": float((r24[m] ** 2).sum())}
    return out


def _copy_state(st: dict) -> dict:
    out = {}
    for k, v in st.items():
        if isinstance(v, np.ndarray):
            out[k] = v.copy()
        elif isinstance(v, dict):
            out[k] = {a: b.copy() for a, b in v.items()}
        else:
            out[k] = v
    return out
