"""Change 2 to the protocol (protocol-r1-change-2.json), decided after the first results and after review, labelled so on
the page. Readings on the corrected sessions (STUDY_SOURCE_RULE=declared, the default of tools/ga4lib.py):

1. referral_split: the attribution table with referral split into outside referral sites and the store's own hosts.
2. store_host_return_attribution: last non-direct with store-host sessions treated like direct.
3. store_host_return_rates: channel purchase rates with each store-host session credited to the channel of the same
   user's latest earlier session in the previous 30 days that is known, not direct and not a store-host session.
4. return_counts: how many store-host sessions, and how many of all sessions, follow an earlier session of the same user.

Usage: python3 -B tools/change_2.py <parquet dir> <temp dir>   (writes $STUDY_RESULTS/change_2.json, default results/corrected)
"""
import json
import os
import sys
from collections import Counter
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" / "corrected"))
DAYS30 = 30 * 24 * 3600 * 1_000_000  # the declared last non-direct lookback, in event-timestamp microseconds
STORE = "ch = 'referral' AND src0 LIKE '%googlemerchandisestore%'"  # the store-host rule of Change 1
LABELS = ["direct", "organic search", "paid search", "outside referral", "store host", "email", "other tagged", "unknown"]
RULES = ["session_scope", "user_first_touch", "last_non_direct", "last_non_direct_store_host_as_direct"]
STAGE_COLS = ["view_item", "add_to_cart", "begin_checkout", "purchase"]


def session_table(con, t="ev"):
    """_c2: every session with its channel, its label (referral split by host), and the two 30-day lookbacks."""
    ga4lib.session_arrays(con, t)  # builds the temp table _sess: every session, its channel, and its reach in both reads
    con.execute(f"""CREATE OR REPLACE TEMP TABLE _c2 AS
      WITH s AS (SELECT *, coalesce({STORE}, false) AS store FROM _sess),
      l AS (SELECT *, CASE WHEN store THEN 'store host' WHEN ch = 'referral' THEN 'outside referral' ELSE ch END AS lab FROM s)
      SELECT *,
        last_value(CASE WHEN ch NOT IN ('direct', 'unknown') THEN lab END IGNORE NULLS)
          OVER (PARTITION BY u ORDER BY first_ts RANGE BETWEEN {DAYS30} PRECEDING AND 1 PRECEDING) AS prior_lab,
        last_value(CASE WHEN ch NOT IN ('direct', 'unknown') AND NOT store THEN lab END IGNORE NULLS)
          OVER (PARTITION BY u ORDER BY first_ts RANGE BETWEEN {DAYS30} PRECEDING AND 1 PRECEDING) AS prior_outside,
        row_number() OVER (PARTITION BY u ORDER BY first_ts, sid) AS nth,
        lag(first_ts) OVER (PARTITION BY u ORDER BY first_ts, sid) AS prev_first
      FROM l""")


def return_counts(con):
    q = lambda s: con.execute(s).fetchone()
    store, store_prev, store_prev_30, all_s, all_prev = q(f"""SELECT count(*) FILTER (WHERE store),
        count(*) FILTER (WHERE store AND nth > 1), count(*) FILTER (WHERE store AND nth > 1 AND first_ts - prev_first <= {DAYS30}),
        count(*), count(*) FILTER (WHERE nth > 1) FROM _c2""")
    return {"store_host_sessions": store, "store_host_with_an_earlier_session": store_prev,
            "store_host_with_an_earlier_session_started_within_30_days": store_prev_30,
            "sessions": all_s, "sessions_with_an_earlier_session": all_prev,
            "users": q("SELECT count(DISTINCT u) FROM _c2")[0]}


def return_rates(con, replicates=1000, seed=4):
    """Channel purchase rates in both reads, each store-host session credited to the earlier channel when there is one."""
    con.execute("""CREATE OR REPLACE TEMP TABLE _rr AS SELECT *,
        CASE WHEN store THEN coalesce(prior_outside, 'store host') ELSE lab END AS ch_ret FROM _c2""")
    q = lambda s: con.execute(s).fetchall()
    took = dict(q("SELECT ch_ret, count(*) FROM _rr WHERE store AND prior_outside IS NOT NULL GROUP BY 1 ORDER BY 2 DESC"))
    took_buy = dict(q("SELECT ch_ret, count(*) FROM _rr WHERE store AND prior_outside IS NOT NULL AND r_purchase GROUP BY 1 ORDER BY 2 DESC"))
    kept = q("SELECT count(*), count(*) FILTER (WHERE r_purchase) FROM _rr WHERE store AND prior_outside IS NULL")[0]
    arrays = con.execute(f"""SELECT dense_rank() OVER (ORDER BY u) - 1 AS ui, ch_ret AS ch, coalesce(dev, 'unknown') AS dev,
        {", ".join(f"r_{s}" for s in STAGE_COLS)}, {", ".join(f"b_{s}" for s in STAGE_COLS)} FROM _rr""").fetchnumpy()
    f = ga4lib.funnel(arrays, replicates=replicates, seed=seed)
    counts = {"store_host_sessions_credited_to_an_earlier_channel": sum(took.values()), "credited_to_channel": took,
              "credited_purchase_sessions_to_channel": took_buy, "store_host_sessions_with_no_earlier_channel": kept[0],
              "store_host_purchase_sessions_with_no_earlier_channel": kept[1]}
    return counts, {k: f[k] for k in f if k == "all" or k.startswith("channel:")}


def attribution_rows(con, t="ev"):
    """One row per purchase event kept by the flagged-removed read, with its label under each rule."""
    con.execute(f"CREATE OR REPLACE TEMP TABLE _flag AS {ga4lib.flagged_sql(t)}")
    ft = "channel(p.ts_src, p.ts_med)"
    return con.execute(f"""SELECT dense_rank() OVER (ORDER BY p.u) - 1 AS ui,
        coalesce(s.lab, 'unknown') AS session_scope,
        CASE WHEN {ft} = 'referral' AND p.ts_src LIKE '%googlemerchandisestore%' THEN 'store host'
             WHEN {ft} = 'referral' THEN 'outside referral' ELSE {ft} END AS user_first_touch,
        CASE WHEN coalesce(s.ch, 'unknown') IN ('direct', 'unknown') AND s.prior_lab IS NOT NULL THEN s.prior_lab
             ELSE coalesce(s.lab, 'unknown') END AS last_non_direct,
        CASE WHEN (coalesce(s.ch, 'unknown') IN ('direct', 'unknown') OR coalesce(s.store, false)) AND s.prior_outside IS NOT NULL
             THEN s.prior_outside ELSE coalesce(s.lab, 'unknown') END AS last_non_direct_store_host_as_direct
      FROM {t} p LEFT JOIN _c2 s ON p.u = s.u AND p.sid = s.sid
      WHERE p.name = 'purchase' AND p.eid NOT IN (SELECT eid FROM _flag)""").fetchnumpy()


def attribution(rows, replicates=1000, seed=5):
    """Shares per label under each rule, and differences against session scope with Poisson weights per user (as ga4lib)."""
    ui = rows["ui"].astype(np.int64)
    n = len(ui)
    assert n > 0
    idx = {c: i for i, c in enumerate(LABELS)}
    code = {r: np.array([idx[c] for c in rows[r].astype(str)]) for r in RULES}
    nu = int(ui.max()) + 1
    rng = np.random.default_rng(seed)
    point = {r: np.bincount(code[r], minlength=len(LABELS)) / n for r in RULES}
    boots = {r: np.zeros((replicates, len(LABELS))) for r in RULES}
    for k in range(replicates):
        w = rng.poisson(1.0, nu)[ui]
        tot = w.sum()
        for r in RULES:
            boots[r][k] = np.bincount(code[r], weights=w, minlength=len(LABELS)) / tot
    out = {"orders": n, "labels": LABELS, "shares": {r: {c: float(point[r][idx[c]]) for c in LABELS} for r in RULES},
           "differences_against_session_scope": {}}
    for r in RULES[1:]:
        d = boots[r] - boots["session_scope"]
        out["differences_against_session_scope"][r] = {
            c: {"difference": float(point[r][idx[c]] - point["session_scope"][idx[c]]),
                "ci": [float(np.percentile(d[:, idx[c]], 2.5)), float(np.percentile(d[:, idx[c]], 97.5))]} for c in LABELS}
    # the two referral rows folded back into the declared referral channel, on the same draws
    both = lambda x: x[..., idx["outside referral"]] + x[..., idx["store host"]]
    out["referral_both"] = {"shares": {r: float(both(point[r])) for r in RULES}, "differences_against_session_scope": {}}
    for r in RULES[1:]:
        d = both(boots[r]) - both(boots["session_scope"])
        out["referral_both"]["differences_against_session_scope"][r] = {
            "difference": float(both(point[r]) - both(point["session_scope"])),
            "ci": [float(np.percentile(d, 2.5)), float(np.percentile(d, 97.5))]}
    return out


def merged_back(rows):
    """The split labels folded back into the declared channels, to check them against the declared rules."""
    fold = lambda a: ["referral" if x in ("outside referral", "store host") else x for x in a.astype(str)]
    return {r: fold(rows[r]) for r in RULES[:3]}


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")
    session_table(con)
    counts = return_counts(con)
    rc, rf = return_rates(con)
    rows = attribution_rows(con)
    declared = ga4lib.attribution_rows(con, "ev")  # the declared rules on the same sessions
    back = merged_back(rows)
    joint = lambda cols: Counter(zip(*cols))
    assert joint([back[r] for r in RULES[:3]]) == joint([[str(x) for x in declared[r]] for r in RULES[:3]]), \
        "the split rules do not fold back into the declared rules"
    at = attribution(rows)
    out = {"note": "Change 2 to the protocol (protocol-r1-change-2.json): decided after the first results and after review; "
                   "descriptions on the corrected sessions, not in the predictions",
           "events": n, "source_rule": os.environ.get("STUDY_SOURCE_RULE", "declared"),
           "return_counts": counts, "store_host_return_rates": {"counts": rc, "funnel": rf},
           "attribution_split": at}
    R.mkdir(parents=True, exist_ok=True)
    tmp = R / "change_2.json.tmp"
    tmp.write_text(json.dumps(out, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    os.replace(tmp, R / "change_2.json")
    print("wrote", R / "change_2.json", flush=True)
    print(json.dumps(counts))
    print(json.dumps(rc))
    for k, v in rf.items():
        print("return", 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"]])
    print("orders", at["orders"])
    for c in LABELS:
        print("share", c, [round(100 * at["shares"][r][c], 2) for r in RULES],
              [(round(100 * at["differences_against_session_scope"][r][c]["difference"], 2),
                [round(100 * x, 2) for x in at["differences_against_session_scope"][r][c]["ci"]]) for r in RULES[1:]])


if __name__ == "__main__":
    main()
