"""Change 1 to the protocol (protocol-r1-change-1.json), decided after the first results and after review, labelled so on
the page. Two readings on the local copy of the export; the money sweep is computed in site/render.py.

1. store_host_merge: a session whose source is the store's own host is merged into the same user's previous session when it
   starts within 30 minutes of that session's last event, and the funnel is read again in both reads.
2. window_transitions: inside the stable window, each step follows the same sessions (a later-stage event at or after the
   earliest earlier-stage event), with intervals over users, and each step's order check.

The frozen functions of tools/ga4lib.py are called, not changed. Usage: python3 -B tools/after_review.py <parquet dir> <temp dir>
"""
import json
import os
import sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tools"))
import ga4lib  # noqa: E402
import results_dir  # noqa: E402

R = Path(os.environ.get("STUDY_RESULTS", ROOT / "results"))
WINDOW = ("20201129", "20210123")  # the stable window of tools/added_later.py
GAP_US = 30 * 60 * 1_000_000        # the protocol's 30-minute inactivity gap, in event-timestamp microseconds
DAY_US = 24 * 3600 * 1_000_000
STORE = "ch = 'referral' AND src0 LIKE '%googlemerchandisestore%'"
STAGE_COLS = ["view_item", "add_to_cart", "begin_checkout", "purchase"]


def merged_sessions(con):
    """Visits after the store-host merge, one row each, with the columns ga4lib.funnel() reads; plus the merge counts."""
    ga4lib.session_arrays(con, "ev")  # builds the temp table _sess: every session, its channel, and its reach in both reads
    con.execute(f"""CREATE OR REPLACE TEMP TABLE _m AS
      WITH l AS (SELECT u, sid, max(ts) AS last_ts FROM ev WHERE sid IS NOT NULL GROUP BY u, sid),
      s AS (SELECT _sess.*, l.last_ts, ({STORE}) AS store FROM _sess JOIN l USING (u, sid)),
      o AS (SELECT *, lag(last_ts) OVER (PARTITION BY u ORDER BY first_ts, sid) AS prev_last FROM s),
      g AS (SELECT *, CASE WHEN store AND prev_last IS NOT NULL AND first_ts - prev_last <= {GAP_US} THEN 0 ELSE 1 END AS starts FROM o)
      SELECT *, sum(starts) OVER (PARTITION BY u ORDER BY first_ts, sid ROWS UNBOUNDED PRECEDING) AS grp FROM g""")
    stage_or = ", ".join(f"bool_or(r_{s}) AS r_{s}, bool_or(b_{s}) AS b_{s}" for s in STAGE_COLS)
    con.execute(f"""CREATE OR REPLACE TEMP TABLE _v AS
      SELECT u, grp, arg_min(CASE WHEN store THEN 'store host' ELSE ch END, first_ts) AS ch,
        arg_min(coalesce(dev, 'unknown'), first_ts) AS dev, count(*) AS n_sessions, {stage_or}
      FROM _m GROUP BY u, grp""")
    q = lambda s: con.execute(s).fetchone()
    store, merged, merged_buy, store_buy, no_prev, prev_30d = q(f"""SELECT count(*) FILTER (WHERE store),
        count(*) FILTER (WHERE store AND starts = 0), count(*) FILTER (WHERE store AND starts = 0 AND r_purchase),
        count(*) FILTER (WHERE store AND r_purchase), count(*) FILTER (WHERE store AND prev_last IS NULL),
        count(*) FILTER (WHERE store AND prev_last IS NOT NULL AND first_ts - prev_last <= {30 * DAY_US}) FROM _m""")
    into = dict(con.execute("""SELECT v.ch, count(*) FROM _m m JOIN _v v USING (u, grp) WHERE m.store AND m.starts = 0
        GROUP BY 1 ORDER BY 2 DESC""").fetchall())
    into_buy = dict(con.execute("""SELECT v.ch, count(*) FROM _m m JOIN _v v USING (u, grp) WHERE m.store AND m.starts = 0
        AND m.r_purchase GROUP BY 1 ORDER BY 2 DESC""").fetchall())
    sessions, visits = q("SELECT (SELECT count(*) FROM _m), (SELECT count(*) FROM _v)")
    assert sessions - visits == merged, (sessions, visits, merged)
    arrays = con.execute(f"""SELECT dense_rank() OVER (ORDER BY u) - 1 AS ui, ch, dev,
        {", ".join(f"r_{s}" for s in STAGE_COLS)}, {", ".join(f"b_{s}" for s in STAGE_COLS)} FROM _v""").fetchnumpy()
    counts = {"sessions": sessions, "visits_after_merge": visits, "store_host_sessions": store,
              "store_host_purchase_sessions": store_buy, "merged": merged, "merged_purchase_sessions": merged_buy,
              "store_host_with_no_earlier_session": no_prev, "store_host_with_an_earlier_session_within_30_days": prev_30d,
              "merged_into_channel": into, "merged_purchase_sessions_into_channel": into_buy}
    return arrays, counts


def window_transitions(con, replicates=1000, seed=6):
    """Steps that follow the same sessions inside the window, per channel, as exported, with Poisson weights per user."""
    con.execute(f"CREATE OR REPLACE TEMP VIEW ev_w AS SELECT * FROM ev WHERE d BETWEEN '{WINDOW[0]}' AND '{WINDOW[1]}'")
    agg = ", ".join(f"min(ts) FILTER (WHERE name = '{s}') AS lo_{s}, max(ts) FILTER (WHERE name = '{s}') AS hi_{s}"
                    for s in STAGE_COLS)
    con.execute(f"""CREATE OR REPLACE TEMP TABLE _t AS
      WITH s AS ({ga4lib.sessions_sql('ev_w')}), t AS (SELECT u, sid, {agg} FROM ev_w WHERE sid IS NOT NULL GROUP BY u, sid)
      SELECT s.u, channel(s.src0, s.med0) AS ch, t.* EXCLUDE (u, sid) FROM s JOIN t USING (u, sid)""")
    pairs = [("view_item", "add_to_cart"), ("add_to_cart", "begin_checkout"), ("begin_checkout", "purchase")]
    cols = ["lo_view_item IS NOT NULL AS has_view_item"]
    cols += [f"lo_{s} IS NOT NULL AS has_{s}" for s in STAGE_COLS[1:]]
    cols += [f"(lo_{x} IS NOT NULL AND hi_{y} IS NOT NULL AND hi_{y} >= lo_{x}) AS go_{x}" for x, y in pairs]
    cols += [f"(hi_{y} IS NOT NULL AND NOT coalesce(lo_{x} <= hi_{y}, false)) AS orphan_{y}" for x, y in pairs]
    a = con.execute(f"SELECT dense_rank() OVER (ORDER BY u) - 1 AS ui, ch, {', '.join(cols)} FROM _t").fetchnumpy()
    ui = a["ui"].astype(np.int64)
    ch = a["ch"].astype(str)
    chans = sorted(set(ch))
    cid = np.array([chans.index(c) for c in ch], dtype=np.int64)
    # numerator and denominator columns for the four steps: session to view, view to cart, cart to checkout, checkout to purchase
    one = np.ones(len(ui), dtype=np.float64)
    num = [a["has_view_item"], a["go_view_item"], a["go_add_to_cart"], a["go_begin_checkout"]]
    den = [one, a["has_view_item"], a["has_add_to_cart"], a["has_begin_checkout"]]
    num = [np.asarray(x, dtype=np.float64) for x in num]
    den = [np.asarray(x, dtype=np.float64) for x in den]
    purch = np.asarray(a["has_purchase"], dtype=np.float64)
    nu = int(ui.max()) + 1
    k = len(chans)
    rng = np.random.default_rng(seed)
    bn = np.zeros((replicates, k, 4))
    bd = np.zeros((replicates, k, 4))
    for r in range(replicates):
        w = rng.poisson(1.0, nu)[ui].astype(np.float64)
        for j in range(4):
            bn[r, :, j] = np.bincount(cid, weights=w * num[j], minlength=k)
            bd[r, :, j] = np.bincount(cid, weights=w * den[j], minlength=k)
    pn = np.stack([np.bincount(cid, weights=num[j], minlength=k) for j in range(4)], axis=1)
    pd = np.stack([np.bincount(cid, weights=den[j], minlength=k) for j in range(4)], axis=1)
    pp = np.bincount(cid, weights=purch, minlength=k)

    def cell(n_b, d_b, n_p, d_p, p_p):
        with np.errstate(divide="ignore", invalid="ignore"):
            rb = n_b / d_b
        out = {"sessions": int(d_p[0]), "numerators": [int(x) for x in n_p], "denominators": [int(x) for x in d_p],
               "step": [float(n_p[j] / d_p[j]) if d_p[j] else None for j in range(4)], "step_ci": [],
               "purchase_sessions": int(p_p), "session_to_purchase": float(p_p / d_p[0]) if d_p[0] else None}
        for j in range(4):
            x = rb[:, j][np.isfinite(rb[:, j])]
            out["step_ci"].append([float(np.percentile(x, 2.5)), float(np.percentile(x, 97.5))] if len(x) else [None, None])
        return out

    res = {"all": cell(bn.sum(axis=1), bd.sum(axis=1), pn.sum(axis=0), pd.sum(axis=0), pp.sum())}
    for i, c in enumerate(chans):
        res[f"channel:{c}"] = cell(bn[:, i, :], bd[:, i, :], pn[i], pd[i], pp[i])
    checks = {}
    for x, y in pairs:
        has_y = np.asarray(a[f"has_{y}"], dtype=bool)
        orphan = np.asarray(a[f"orphan_{y}"], dtype=bool)
        checks[f"{y}_with_no_{x}_at_or_before"] = {"num": int(orphan.sum()), "den": int(has_y.sum()),
                                                  "rate": float(orphan.sum() / has_y.sum()) if has_y.sum() else None}
    return res, checks


def main():
    pq, temp = sys.argv[1], sys.argv[2]
    results_dir.check(R)
    con = ga4lib.connect(threads=4, temp=temp)
    n = ga4lib.load(con, f"{pq}/events_*.parquet")
    arrays, counts = merged_sessions(con)
    fm = ga4lib.funnel(arrays, replicates=1000, seed=4)
    wt, wchecks = window_transitions(con)
    keep = lambda f: {k: f[k] for k in f if k == "all" or k.startswith("channel:")}
    out = {"note": "Change 1 to the protocol (protocol-r1-change-1.json): decided after the first results and after review; "
                   "descriptions, not in the predictions",
           "events": n, "store_host_merge": {"counts": counts, "funnel": keep(fm)},
           "window": list(WINDOW), "window_transitions": wt, "window_order_checks": wchecks}
    R.mkdir(exist_ok=True)
    tmp = R / "after_review.json.tmp"
    tmp.write_text(json.dumps(out, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    os.replace(tmp, R / "after_review.json")
    print("wrote after_review.json", flush=True)
    print(json.dumps(counts))
    for k, v in keep(fm).items():
        print("merge", k, v["sessions"], v["reach_A"][4], round(100 * v["overall_A"], 3), [round(100 * x, 3) for x in v["overall_A_ci"]],
              round(100 * v["overall_B"], 3), [round(100 * x, 3) for x in v["overall_B_ci"]])
    for k, v in wt.items():
        print("window", k, v["sessions"], [None if s is None else round(100 * s, 1) for s in v["step"]],
              [[round(100 * a, 1) for a in c] if c[0] is not None else c for c in v["step_ci"]])
    print("order checks", {k: round(100 * v["rate"], 2) for k, v in wchecks.items()})


if __name__ == "__main__":
    main()
