"""The checks, thresholds frozen in protocol-r1.json. Each returns the first rep week it fires, or None. Evaluated every
rep week of the test and its read-out. Five groups: dbt tests in the warehouse, the connector's own report, reading the CRM
back against the mart, the experiment's integrity, and drift in the mart's score."""
import numpy as np

import pipeline as P

GROUPS = {"warehouse": [], "connector": ["connector_status", "connector_rows"],
          "readback": ["score_match", "score_fresh", "hot_count", "arm_match", "live_coverage", "human_fields"],
          "integrity": ["arm_balance", "holdout_contact", "contact_rate", "arm_stable"],
          "drift": ["hot_share", "score_psi", "entrant_flow"]}
FIRST, MIN_N = P.FIRST_TEST_WEEK + 1, 50


def psi(a, b):
    """Population stability of a against b over b's deciles."""
    edges = np.unique(np.quantile(b, np.linspace(0, 1, 11)))
    if edges.size < 3:
        return 0.0
    edges[0], edges[-1] = -np.inf, np.inf
    pa = np.maximum(np.histogram(a, edges)[0] / a.size, 1e-4)
    pb = np.maximum(np.histogram(b, edges)[0] / b.size, 1e-4)
    return float(((pa - pb) * np.log(pa / pb)).sum())


def drift_checks(wh, weeks):
    """Depends only on the mart, so one warehouse is checked once."""
    out = {"hot_share": None, "score_psi": None, "entrant_flow": None}
    s = wh["score"]
    entry = wh["entry"][wh["is_score"]]
    for w in range(FIRST, weeks + 1):
        cur = s[w - 1]
        ok = ~np.isnan(cur)
        prev = s[w - 5:w - 1]
        hot_now = (cur[ok] >= P.HOT_CUT).mean()
        hot_prev = np.nanmean(prev >= P.HOT_CUT, axis=1).mean()
        if out["hot_share"] is None and abs(hot_now / max(hot_prev, 1e-6) - 1) > 0.30:
            out["hot_share"] = w
        if out["score_psi"] is None and psi(cur[ok], prev[~np.isnan(prev)]) > 0.10:
            out["score_psi"] = w
        if out["entrant_flow"] is None and w - 1 <= P.LAST_TEST_WEEK and w - 5 >= P.FIRST_TEST_WEEK:
            flow = (entry == w - 1).sum()
            trail = np.mean([(entry == k).sum() for k in range(w - 5, w - 1)])
            if trail >= 20 and (flow < 0.5 * trail or flow > 2.0 * trail):
                out["entrant_flow"] = w
    return out


def run(co, wh, tests, crm, contact, fault, ctx, drift):
    weeks = co.weeks
    fires = {k: None for g in GROUPS.values() for k in g}
    for k, bad in tests.items():
        fires["dbt:" + k] = fault.onset if bad > 0 else None
    fires.update(drift)
    enrolled = wh["is_score"] & (wh["entry"] >= 0)
    arm_at_entry = wh["contact_arm"].copy()
    prev_dnc = int(crm.dnc[FIRST - 1].sum())

    def fire(name, w, cond):
        if fires[name] is None and cond:
            fires[name] = w

    for w in range(FIRST, weeks + 1):
        mart = wh["score"][w - 1]
        has = ~np.isnan(mart)
        crm_s = crm.score[w]
        rep_s, _ = fault.rep_view(w, crm_s, crm.holdout[w], ctx)
        arm = fault.mart_arm(w, wh, ctx)
        fire("connector_status", w, crm.status[w] != "success")
        fire("connector_rows", w, crm.rows_written[w] < 0.99 * crm.rows_payload[w])
        with np.errstate(invalid="ignore"):
            fire("score_match", w, (np.abs(crm_s[has] - mart[has]) <= 1.0).mean() < 0.99)
            hot_crm = int((crm_s >= crm.cut[w]).sum())
        fire("score_fresh", w, (crm.score_week[w][has] == w - 1).mean() < 0.99)
        hot_mart = int((mart[has] >= P.HOT_CUT).sum())
        fire("hot_count", w, abs(hot_crm - hot_mart) > 0.05 * max(hot_mart, 1))
        fire("arm_match", w, (crm.holdout[w] == (~arm).astype(np.int8)).mean() < 0.995)
        fire("live_coverage", w, np.isnan(rep_s[has]).mean() > 0.01)
        n_dnc = int(crm.dnc[w].sum())
        fire("human_fields", w, n_dnc < 0.99 * prev_dnc)
        prev_dnc = n_dnc
        in_so_far = enrolled & (wh["entry"] <= w - 1)
        a, b = int((in_so_far & arm).sum()), int((in_so_far & ~arm).sum())
        if a + b >= MIN_N:
            fire("arm_balance", w, abs(a - 0.6 * (a + b)) / np.sqrt(0.24 * (a + b)) > 3.29)
        done = (contact >= 0) & (contact <= w)
        hold = enrolled & ~arm & (wh["entry"] <= w - 2)
        if hold.sum() >= MIN_N:
            fire("holdout_contact", w, done[hold].mean() > 0.05)
        cont = enrolled & arm & (wh["entry"] <= w - 3)
        if cont.sum() >= MIN_N:
            fire("contact_rate", w, done[cont].mean() < 0.70)
        fire("arm_stable", w, (arm[in_so_far] != arm_at_entry[in_so_far]).any())
    return fires


def wrong_weeks(co, wh, crm, fault, ctx, clean_score):
    """Account-weeks in which the hot band a rep reads differs from the clean mart's, per rep week of the test."""
    out = {}
    for w in range(FIRST, co.weeks + 1):
        rep_s, _ = fault.rep_view(w, crm.score[w], crm.holdout[w], ctx)
        a = np.nan_to_num(rep_s, nan=-1) >= crm.cut[w]
        b = np.nan_to_num(clean_score[w - 1], nan=-1) >= P.HOT_CUT
        out[w] = int((a != b).sum())
    return out
