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

1. earlier_cart: checkout sessions with no add to cart in the session, and whether the same user added to cart in another,
   earlier session (within the previous 30 days, and at any earlier time), by period and inside the stable window; the
   same shares among checkout sessions that hold an add to cart, for comparison; and the declared expectation's verdict.
2. no_source_split: the sessions with no usable source, split into no parameter at all, a placeholder string on the event
   the source rule reads, and one of the two values missing there.

Usage: python3 -B tools/change_3.py <parquet dir> <temp dir>   (writes $STUDY_RESULTS/change_3.json, default results/corrected)
"""
import json
import os
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tools"))
import after_review  # noqa: E402
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
LATE_FROM = "20201115"               # the weekly split: the first two weeks are 1 to 14 November
WINDOW = after_review.WINDOW         # the stable window of Change 1
PH_STRINGS = "('', '<Other>', '(data deleted)', '(not set)')"  # the declared placeholder strings; null is the fifth placeholder


def _earlier(sessions):
    """SQL joining each checkout session in the table named by `sessions` (u, sid, first_ts) to the latest add_to_cart event of
    the same user in another session with a timestamp before the session's first event."""
    return f"""
      WITH c AS (SELECT u, sid AS csid, ts FROM ev WHERE name = 'add_to_cart' AND sid IS NOT NULL),
      j AS (SELECT s.u, s.sid, max(c.ts) AS last_cart FROM {sessions} s JOIN c ON s.u = c.u AND c.csid <> s.sid AND c.ts < s.first_ts
            GROUP BY 1, 2)
      SELECT s.*, j.last_cart IS NOT NULL AS cart_any, coalesce(j.last_cart >= s.first_ts - {DAYS30}, false) AS cart_30
      FROM {sessions} s LEFT JOIN j USING (u, sid)"""


def _counts(con, table, where):
    n, n30, nany = con.execute(f"SELECT count(*), count(*) FILTER (WHERE cart_30), count(*) FILTER (WHERE cart_any) FROM {table} "
                               f"WHERE {where}").fetchone()
    return {"sessions": n, "earlier_cart_within_30_days": n30, "earlier_cart_any_time": nany,
            "share_within_30_days": (n30 / n) if n else None, "share_any_time": (nany / n) if n else None}


def earlier_cart(con, t="ev"):
    """The whole-period check as declared (no add_to_cart in the session), by the session's first day."""
    con.execute(f"CREATE OR REPLACE TEMP TABLE _c3s AS SELECT u, sid, first_ts, d0, r_add_to_cart FROM ({ga4lib.sessions_sql(t)}) "
                f"WHERE r_begin_checkout")
    con.execute(f"CREATE OR REPLACE TEMP TABLE _c3j AS {_earlier('_c3s')}")
    periods = {"whole_period": "true", "first_two_weeks": f"d0 < '{LATE_FROM}'", "from_15_november": f"d0 >= '{LATE_FROM}'"}
    out = {}
    for name, cond in periods.items():
        out[name] = {"no_cart": _counts(con, "_c3j", f"{cond} AND NOT r_add_to_cart"),
                     "with_cart": _counts(con, "_c3j", f"{cond} AND r_add_to_cart")}
    return out


def window_earlier_cart(con):
    """Inside the stable window: the sessions Change 1's order check flags (no add_to_cart at or before the last begin_checkout),
    read from the window's events; the earlier cart is looked up over the whole export."""
    con.execute(f"CREATE OR REPLACE TEMP VIEW ev_w3 AS SELECT * FROM ev WHERE d BETWEEN '{WINDOW[0]}' AND '{WINDOW[1]}'")
    con.execute(f"""CREATE OR REPLACE TEMP TABLE _w3s AS
      WITH s AS ({ga4lib.sessions_sql('ev_w3')}),
      t AS (SELECT u, sid, min(ts) FILTER (WHERE name = 'add_to_cart') AS lo_cart, max(ts) FILTER (WHERE name = 'begin_checkout') AS hi_chk
            FROM ev_w3 WHERE sid IS NOT NULL GROUP BY u, sid)
      SELECT s.u, s.sid, s.first_ts, coalesce(t.lo_cart <= t.hi_chk, false) AS cart_before
      FROM s JOIN t USING (u, sid) WHERE t.hi_chk IS NOT NULL""")
    con.execute(f"CREATE OR REPLACE TEMP TABLE _w3j AS {_earlier('_w3s')}")
    return {"window": list(WINDOW), "no_cart_at_or_before": _counts(con, "_w3j", "NOT cart_before"),
            "cart_at_or_before": _counts(con, "_w3j", "cart_before")}


def no_source_split(con, t="ev"):
    con.execute(f"CREATE OR REPLACE TEMP TABLE _n3 AS {ga4lib.sessions_sql(t)}")
    isph = lambda x: f"coalesce({x} IN {PH_STRINGS}, false)"
    tagged_ph = "n_with_source > 0 AND (is_ph(src0) OR is_ph(med0))"
    q = con.execute(f"""SELECT count(*), count(*) FILTER (WHERE is_ph(src0) OR is_ph(med0)), count(*) FILTER (WHERE n_with_source = 0),
        count(*) FILTER (WHERE {tagged_ph} AND ({isph('src0')} OR {isph('med0')})),
        count(*) FILTER (WHERE {tagged_ph} AND NOT {isph('src0')} AND NOT {isph('med0')}) FROM _n3""").fetchone()
    sessions, no_usable, a, b, c = q
    assert a + b + c == no_usable, q
    show = lambda x: f"CASE WHEN {x} IS NULL THEN 'missing' WHEN {isph(x)} THEN {x} ELSE 'usable value' END"
    pairs = con.execute(f"""SELECT {show('src0')} AS s, {show('med0')} AS m, count(*) AS n FROM _n3
        WHERE {tagged_ph} AND ({isph('src0')} OR {isph('med0')}) GROUP BY 1, 2 ORDER BY 3 DESC, 1, 2 LIMIT 12""").fetchall()
    missing = con.execute(f"""SELECT CASE WHEN src0 IS NULL AND med0 IS NULL THEN 'both missing' WHEN src0 IS NULL THEN 'source missing'
        ELSE 'medium missing' END AS w, count(*) FROM _n3 WHERE {tagged_ph} AND NOT {isph('src0')} AND NOT {isph('med0')}
        GROUP BY 1 ORDER BY 2 DESC""").fetchall()
    return {"sessions": sessions, "no_usable_source": no_usable, "no_source_or_medium_on_any_event": a,
            "placeholder_string_on_the_event_read": b, "one_value_missing_on_the_event_read": c,
            "placeholder_pairs": [{"source": s, "medium": m, "sessions": n} for s, m, n in pairs],
            "one_value_missing_by_value": dict(missing)}


def expectation(ec):
    share = ec["from_15_november"]["no_cart"]["share_within_30_days"]
    return {"text": "From 15 November on, fewer than half of the checkout sessions with no add to cart have an add to cart by the same "
                    "user in an earlier session within the previous 30 days.",
            "observed_share": share, "verdict": "held" if share < 0.5 else "missed"}


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")
    ec = earlier_cart(con)
    wc = window_earlier_cart(con)
    ns = no_source_split(con)
    out = {"note": "Change 3 to the protocol (protocol-r1-change-3.json): decided after the first results and after a third review; "
                   "descriptions on the corrected sessions, not in the predictions",
           "events": n, "source_rule": os.environ.get("STUDY_SOURCE_RULE", "declared"),
           "earlier_cart": ec, "earlier_cart_in_window": wc, "expectation": expectation(ec), "no_source_split": ns}
    R.mkdir(parents=True, exist_ok=True)
    tmp = R / "change_3.json.tmp"
    tmp.write_text(json.dumps(out, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    os.replace(tmp, R / "change_3.json")
    print("wrote", R / "change_3.json", flush=True)
    for k, v in ec.items():
        for g, c in v.items():
            print("earlier cart", k, g, c["sessions"], c["earlier_cart_within_30_days"], c["earlier_cart_any_time"])
    for g in ("no_cart_at_or_before", "cart_at_or_before"):
        c = wc[g]
        print("window", g, c["sessions"], c["earlier_cart_within_30_days"], c["earlier_cart_any_time"])
    print("expectation", out["expectation"]["verdict"], round(100 * out["expectation"]["observed_share"], 2))
    print("no source split", ns["sessions"], ns["no_usable_source"], ns["no_source_or_medium_on_any_event"],
          ns["placeholder_string_on_the_event_read"], ns["one_value_missing_on_the_event_read"])
    print("missing", json.dumps(ns["one_value_missing_by_value"]))
    for p in ns["placeholder_pairs"]:
        print("pair", p["source"], "|", p["medium"], p["sessions"])


if __name__ == "__main__":
    main()
