"""Score the declared questions on the dbt model and write results/summary-<cohort day>.json.

Reads the DuckDB file dbt built (<work>/model.duckdb). Every rule comes from protocol-r1.json.
Usage: python3 -B tools/analyze.py <work dir> <cohort day>
"""
from __future__ import annotations

import json
import os
import sys

import duckdb
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
PROTOCOL = json.load(open(os.path.join(ROOT, "protocol-r1.json"), encoding="utf-8"))
CANDIDATES = list(PROTOCOL["candidates"])
INPUTS = list(PROTOCOL["inputs"])
SEED = 20240910
B = 1000


def avg_ranks(x: np.ndarray) -> np.ndarray:
    u, inv, cnt = np.unique(x, return_inverse=True, return_counts=True)
    ends = np.cumsum(cnt)
    starts = ends - cnt + 1
    return ((starts + ends) / 2.0)[inv]


def auc(score: np.ndarray, y: np.ndarray) -> float:
    """Mann-Whitney AUC; ties count one half."""
    n1 = int(y.sum())
    n0 = len(y) - n1
    r = avg_ranks(score)
    return float((r[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))


def rate(y) -> float:
    y = np.asarray(y)
    return float(y.mean()) if len(y) else float("nan")


def main(work: str, cohort_day: str) -> None:
    con = duckdb.connect(os.path.join(work, "model.duckdb"), read_only=True)
    q = lambda s: con.execute(s).fetchall()
    cols = ["actor_id", "is_automation", "is_bot_login", "first_action", "events_day0", "second_day",
            "activated", "retained", "retained_any_event"] + CANDIDATES + INPUTS
    rows = q(f"select {', '.join(cols)} from mart_newcomer order by actor_id")
    D = {c: np.array([r[i] for r in rows]) for i, c in enumerate(cols)}
    members = len(rows)
    auto = D["is_automation"].astype(bool)
    keep = ~auto
    A = {c: v[keep] for c, v in D.items()}
    y = A["retained"].astype(int)
    n = int(keep.sum())

    # ---- census of the data read
    hours = q("select window_name, count(*), sum(case when is_missing then 1 else 0 end),"
              " sum(case when is_short then 1 else 0 end), sum(events), sum(events - distinct_ids),"
              " sum(bot_login_events), sum(band_events) from stg_hours group by 1 order by 1")
    census = {w: {"hours": h, "missing": m, "short": s, "events": int(ev or 0),
                  "dup_within_files": int(d or 0), "bot_login_events": int(b or 0),
                  "band_events": int(be or 0)} for w, h, m, s, ev, d, b, be in hours}
    short_list = [r[0] for r in q("select source_hour from stg_hours where is_missing or is_short order by 1")]
    raw_rows = q("select count(*) from read_parquet('" + os.path.join(work, "hours", "*.parquet") + "')")[0][0]
    dedup_rows = q("select count(*) from stg_events")[0][0]
    multi_copy = q("select count(*) from stg_events where copies > 1")[0][0]
    late = q("select count(*) from stg_events where strftime(created_at, '%Y-%m-%d-') ||"
             " cast(hour(created_at) as varchar) <> source_hour")[0][0]
    outside = q("select count(*) from stg_events where not (day_index between 0 and 6"
                " or day_index between 84 and 90)")[0][0]
    band = json.load(open(os.path.join(work, "band.json")))
    band_accounts = q("select count(*) from dim_account")[0][0]
    not_day0 = q("select count(*) from dim_account where not is_cohort_member")[0][0]
    auto_parts = {
        "bot_login": int(D["is_bot_login"].astype(bool).sum()),
        "any_rule": int(auto.sum()),
    }
    auto_parts["volume_rule_only"] = auto_parts["any_rule"] - int(
        (D["is_bot_login"].astype(bool) & auto).sum())
    total_events = sum(v["events"] for v in census.values())
    bytes_read = sum(json.load(open(os.path.join(work, "hours", f)))["bytes"]
                     for f in os.listdir(os.path.join(work, "hours"))
                     if f.endswith(".census.json")
                     and not json.load(open(os.path.join(work, "hours", f))).get("missing"))

    # ---- candidates: AUC and bootstrap
    rng = np.random.default_rng(SEED)
    point = {c: auc(A[c].astype(float), y) for c in CANDIDATES}
    boots = {c: [] for c in CANDIDATES}
    for _ in range(B):
        idx = rng.integers(0, n, n)
        yb = y[idx]
        for c in CANDIDATES:
            boots[c].append(auc(A[c][idx].astype(float), yb))
    boots = {c: np.array(v) for c, v in boots.items()}
    ci = lambda a: [float(np.percentile(a, 2.5)), float(np.percentile(a, 97.5))]
    winner = max(CANDIDATES, key=lambda c: point[c])
    cand = {}
    for c in CANDIDATES:
        diff = boots[winner] - boots[c]
        cand[c] = {"auc": point[c], "ci": ci(boots[c]),
                   "winner_minus_this": float(point[winner] - point[c]),
                   "winner_minus_this_ci": ci(diff) if c != winner else [0.0, 0.0],
                   "mean": float(A[c].mean()), "median": float(np.median(A[c]))}
    beats = {c: c == winner or cand[c]["winner_minus_this_ci"][0] > 0 for c in CANDIDATES}
    ad_minus_ev = boots["active_days_w1"] - boots["events_w1"]

    # ---- the default check: top decile by events against top decile by active days
    def top(c):
        cut = np.percentile(A[c], 90)
        m = A[c] >= cut
        return {"cut": float(cut), "accounts": int(m.sum()), "share": float(m.mean()),
                "retention": rate(y[m])}
    deciles = {"events_w1": top("events_w1"), "active_days_w1": top("active_days_w1")}
    burst = (A["active_days_w1"] == 1) & (A["events_w1"] >= 20)
    steady = (A["active_days_w1"] >= 4) & (A["events_w1"] <= 10)
    contrast = {"burst": {"rule": "one active day, 20 or more events", "accounts": int(burst.sum()),
                          "retention": rate(y[burst])},
                "steady": {"rule": "4 or more active days, 10 or fewer events",
                           "accounts": int(steady.sum()), "retention": rate(y[steady])}}

    # ---- retention curves
    by_days = [{"active_days": d, "accounts": int((A["active_days_w1"] == d).sum()),
                "retained": int(y[A["active_days_w1"] == d].sum()),
                "retention": rate(y[A["active_days_w1"] == d])} for d in range(1, 8)]
    ev_bands = [(1, 1), (2, 4), (5, 9), (10, 19), (20, 49), (50, 10**9)]
    by_events = []
    for lo, hi in ev_bands:
        m = (A["events_w1"] >= lo) & (A["events_w1"] <= hi)
        by_events.append({"band": f"{lo}+" if hi > 10**8 else (f"{lo}" if lo == hi else f"{lo}-{hi}"),
                          "accounts": int(m.sum()), "retention": rate(y[m])})

    # ---- inputs: raw and standardised over active-day strata
    strata = [(1, 1), (2, 2), (3, 3), (4, 7)]
    inputs = {}
    for c in INPUTS:
        x = A[c].astype(bool)
        raw = rate(y[x]) - rate(y[~x])
        num, den, used = 0.0, 0, []
        for lo, hi in strata:
            s = (A["active_days_w1"] >= lo) & (A["active_days_w1"] <= hi)
            a, b = s & x, s & ~x
            if a.sum() >= 20 and b.sum() >= 20:
                num += s.sum() * (rate(y[a]) - rate(y[b]))
                den += int(s.sum())
                used.append(f"{lo}" if lo == hi else f"{lo}-{hi}")
        inputs[c] = {"share": float(x.mean()), "accounts": int(x.sum()),
                     "retention_if": rate(y[x]), "retention_if_not": rate(y[~x]),
                     "raw_diff": raw, "std_diff": num / den if den else None, "strata_used": used}
    top_input = max(INPUTS, key=lambda c: inputs[c]["std_diff"] if inputs[c]["std_diff"] is not None else -9)

    # ---- funnel and sizing
    steps = [("active on day 0", np.ones(n, bool)),
             ("active on a second day in week 1", A["second_day"].astype(bool)),
             ("activated", A["activated"].astype(bool)),
             ("retained in week 13", y.astype(bool) & A["activated"].astype(bool))]
    funnel = [{"step": s, "accounts": int(m.sum())} for s, m in steps]
    for i in range(1, len(funnel)):
        funnel[i]["lost"] = funnel[i - 1]["accounts"] - funnel[i]["accounts"]
    biggest = max(funnel[1:], key=lambda f: f["lost"])["step"]
    # sizing: +5 points passing the second-day step, retained at the rate of second-day accounts
    # with the same day-0 event band
    d0b = [(1, 1), (2, 4), (5, 10**9)]
    sd = A["second_day"].astype(bool)
    extra, base_ret = 0.0, rate(y)
    lift_parts = []
    for lo, hi in d0b:
        s = (A["events_day0"] >= lo) & (A["events_day0"] <= hi)
        one_day = s & ~sd
        share_one = one_day.sum() / max(1, (~sd).sum())
        moved = 0.05 * n * share_one
        gain = moved * (rate(y[s & sd]) - rate(y[one_day]))
        extra += gain
        lift_parts.append({"day0_events": f"{lo}+" if hi > 10**8 else (f"{lo}" if lo == hi else f"{lo}-{hi}"),
                           "moved": float(moved), "ret_two_day": rate(y[s & sd]),
                           "ret_one_day": rate(y[one_day])})
    sizing = {"assumption": PROTOCOL["scoring"]["sizing"], "extra_retained_accounts": extra,
              "retention_before": base_ret, "retention_after": base_ret + extra / n,
              "points": 100 * extra / n, "parts": lift_parts}

    # ---- first action mix
    fa = {}
    for a in sorted(set(A["first_action"].tolist())):
        m = A["first_action"] == a
        fa[a] = {"accounts": int(m.sum()), "retention": rate(y[m])}

    # ---- daily active cohort members (non-automation)
    daily = q("select f.day_index, count(distinct f.actor_id) from fct_account_day f"
              " join mart_newcomer m using (actor_id) where not m.is_automation"
              " group by 1 order by 1")

    out = {
        "cohort_day": cohort_day,
        "band": band,
        "data": {"hourly_files_read": sum(v["hours"] - v["missing"] for v in census.values()),
                 "hourly_files_expected": sum(v["hours"] for v in census.values()),
                 "events_read": total_events, "compressed_bytes_read": bytes_read,
                 "census": census, "missing_or_short_hours": short_list,
                 "band_rows_raw": raw_rows, "band_rows_dedup": dedup_rows,
                 "duplicate_rows_dropped": raw_rows - dedup_rows, "events_with_copies": multi_copy,
                 "arrived_in_later_file": late, "outside_windows_dropped": outside},
        "cohort": {"band_accounts_seen": band_accounts, "members": members,
                   "band_accounts_not_first_active_day0": not_day0, "automation": auto_parts,
                   "analysed": n, "retained": int(y.sum()), "retention": rate(y),
                   "retention_any_event": rate(A["retained_any_event"]),
                   "activated": int(A["activated"].sum()), "activation": rate(A["activated"]),
                   "retention_if_activated": rate(y[A["activated"].astype(bool)]),
                   "retention_if_not_activated": rate(y[~A["activated"].astype(bool)])},
        "candidates": cand, "winner": winner, "winner_beats": beats,
        "active_days_minus_events": {"diff": float(point["active_days_w1"] - point["events_w1"]),
                                     "ci": ci(ad_minus_ev)},
        "deciles": deciles, "contrast": contrast,
        "retention_by_active_days": by_days, "retention_by_events": by_events,
        "inputs": inputs, "top_input": top_input,
        "funnel": funnel, "biggest_drop": biggest, "sizing": sizing,
        "first_action": fa, "daily_active": [{"day_index": d, "active": a} for d, a in daily],
        "bootstrap": {"resamples": B, "seed": SEED},
    }
    os.makedirs(os.path.join(ROOT, "results"), exist_ok=True)
    p = os.path.join(ROOT, "results", f"summary-{cohort_day}.json")
    with open(p + ".tmp", "w", encoding="utf-8") as f:
        json.dump(out, f, indent=1)
    os.replace(p + ".tmp", p)
    print(f"VERDICT analyze {cohort_day}: n={n} retention={rate(y):.3f} winner={winner} "
          f"ad-ev={point['active_days_w1'] - point['events_w1']:.3f} top_input={top_input} biggest={biggest}")


if __name__ == "__main__":
    main(os.path.abspath(sys.argv[1]), sys.argv[2])
