"""The three stitching rules (DESIGN.md section 4). None of them reads the true person.

    det = deterministic(rows)                       # user id per key
    model = fit_pairs(rows, det)                    # candidate pairs, features, posteriors
    users = link(det, model, threshold=0.9)         # rule 2
    for users in band_draws(det, model, k, rng):    # rule 3
"""
from __future__ import annotations

import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components

IP_BLOCK_CAP = 120
HANDOFF_DAYS = 3.0


def components(n: int, a: np.ndarray, b: np.ndarray) -> np.ndarray:
    """Connected components of n nodes joined by edges a[i]-b[i]; labels renumbered by first appearance."""
    if n == 0:
        return np.zeros(0, dtype=np.int64)
    g = coo_matrix((np.ones(len(a), dtype=np.int8), (a, b)), shape=(n, n))
    _, lab = connected_components(g, directed=False)
    return renumber(lab)


def renumber(lab: np.ndarray) -> np.ndarray:
    """Relabel 0, 1, 2, ... in order of first appearance."""
    if len(lab) == 0:
        return np.zeros(0, dtype=np.int64)
    _, first, inv = np.unique(lab, return_index=True, return_inverse=True)
    rank = np.empty(len(first), dtype=np.int64)
    rank[np.argsort(first)] = np.arange(len(first))
    return rank[inv.reshape(-1)]


def deterministic(rows: dict) -> np.ndarray:
    """Rule 1: keys sharing a login id, a verified email or a device advertising id are one user."""
    nk = rows["n_keys"]
    a, b = [], []
    base = nk
    for field in ("login", "email", "device"):
        v = rows[field]
        m = (v >= 0) & ~rows["anon"]
        vals, inv = np.unique(v[m], return_inverse=True)
        a.append(rows["key"][m])
        b.append(base + inv)
        base += len(vals)
    a, b = np.concatenate(a), np.concatenate(b)
    lab = components(base, a, b)
    return renumber(lab[:nk])


def key_table(rows: dict) -> dict:
    nk = rows["n_keys"]
    ident = ~rows["anon"]
    first = np.full(nk, np.inf)
    last = np.full(nk, -np.inf)
    np.minimum.at(first, rows["key"], rows["t"])
    np.maximum.at(last, rows["key"], rows["t"])
    ua = np.full(nk, -1)
    ua[rows["key"][ident]] = rows["ua"][ident]
    anon = np.zeros(nk, dtype=bool)
    anon[rows["key"][rows["anon"]]] = True
    return {"first": first, "last": last, "ua": ua, "anon": anon}


def _pairs_from_blocks(keys: np.ndarray, blocks: np.ndarray, cap: int, nk: int) -> np.ndarray:
    """Unique (block, key) incidences -> encoded pairs a*nk+b (a<b), one entry per shared block."""
    inc = np.unique(np.stack([blocks, keys], axis=1), axis=0)
    if len(inc) == 0:
        return np.zeros(0, dtype=np.int64)
    bl, ks = inc[:, 0], inc[:, 1]
    starts = np.flatnonzero(np.r_[True, bl[1:] != bl[:-1]])
    ends = np.r_[starts[1:], len(bl)]
    out = []
    for s, e in zip(starts, ends):
        m = e - s
        if m < 2 or m > cap:
            continue
        kk = ks[s:e]
        i, j = np.triu_indices(m, 1)
        out.append(kk[i] * nk + kk[j])
    return np.concatenate(out) if out else np.zeros(0, dtype=np.int64)


def login_sets(rows: dict, det: np.ndarray) -> dict:
    """{(user, era): frozenset of login ids} for the deterministic users."""
    m = (rows["login"] >= 0) & ~rows["anon"]
    u = det[rows["key"][m]]
    out = {}
    for uu, era, lg in zip(u.tolist(), rows["era"][m].tolist(), rows["login"][m].tolist()):
        out.setdefault((uu, era), set()).add(lg)
    return {k: frozenset(v) for k, v in out.items()}


def conflict(ls: dict, ua: np.ndarray, ub: np.ndarray) -> np.ndarray:
    """Two users each holding login ids of the same era, with none in common, are never linked."""
    res = np.zeros(len(ua), dtype=bool)
    for i, (x, y) in enumerate(zip(ua.tolist(), ub.tolist())):
        for era in (0, 1):
            sx, sy = ls.get((x, era)), ls.get((y, era))
            if sx and sy and not (sx & sy):
                res[i] = True
                break
    return res


def fit_pairs(rows: dict, det: np.ndarray) -> dict:
    """Candidate pairs, their features, the Fellegi-Sunter weights learnt from rule 1's labels, and posteriors."""
    nk = rows["n_keys"]
    kt = key_table(rows)
    ident = ~rows["anon"]
    keys, ips, days = rows["key"][ident], rows["ip"][ident], np.floor(rows["t"][ident]).astype(np.int64)
    by_ip = _pairs_from_blocks(keys, ips, IP_BLOCK_CAP, nk)
    pairs, n_ip = np.unique(by_ip, return_counts=True)
    ipday = ips * 1000 + days
    by_ipday = _pairs_from_blocks(keys, ipday, 10 * IP_BLOCK_CAP, nk)
    pd_u, pd_n = np.unique(by_ipday, return_counts=True)
    n_ipday = np.zeros(len(pairs), dtype=np.int64)
    if len(pd_u):
        pos = np.minimum(np.searchsorted(pd_u, pairs), len(pd_u) - 1)
        hit = pd_u[pos] == pairs
        n_ipday[hit] = pd_n[pos[hit]]
    a, b = pairs // nk, pairs % nk
    f1 = (n_ip >= 2).astype(np.int64)
    f2 = np.minimum(n_ipday, 2).astype(np.int64)
    f3 = (kt["ua"][a] == kt["ua"][b]).astype(np.int64)
    gap_ab = kt["first"][b] - kt["last"][a]
    gap_ba = kt["first"][a] - kt["last"][b]
    handoff = ((gap_ab >= 0) & (gap_ab <= HANDOFF_DAYS)) | ((gap_ba >= 0) & (gap_ba <= HANDOFF_DAYS))
    overlap = (gap_ab < 0) & (gap_ba < 0)
    f4 = np.where(handoff, 0, np.where(overlap, 1, 2)).astype(np.int64)
    feats = np.stack([f1, f2, f3, f4], axis=1)
    levels = [2, 3, 2, 3]
    ua_, ub_ = det[a], det[b]
    ls = login_sets(rows, det)
    same = ua_ == ub_
    conf = np.zeros(len(pairs), dtype=bool)
    if (~same).any():
        conf[~same] = conflict(ls, ua_[~same], ub_[~same])
    pos_m, neg_m = same, conf
    llr = np.zeros(len(pairs))
    weights = []
    for j, L in enumerate(levels):
        cp = np.bincount(feats[pos_m, j], minlength=L) + 1.0
        cn = np.bincount(feats[neg_m, j], minlength=L) + 1.0
        m, u = cp / cp.sum(), cn / cn.sum()
        llr += np.log(m / u)[feats[:, j]]
        weights.append({"m": m.tolist(), "u": u.tolist()})
    n_pos, n_neg = int(pos_m.sum()), int(neg_m.sum())
    prior = (n_pos + 1.0) / (n_pos + n_neg + 2.0)
    logit = np.log(prior / (1 - prior)) + llr
    post = 1.0 / (1.0 + np.exp(-logit))
    scored = ~same & ~conf
    return {"a": a[scored], "b": b[scored], "post": post[scored], "n_candidates": int(len(pairs)),
            "n_pos": n_pos, "n_neg": n_neg, "prior": float(prior), "weights": weights,
            "n_scored": int(scored.sum()), "feats": feats[scored], "levels": levels}


def fit_em(model: dict, max_iter: int = 200, tol: float = 1e-9) -> dict:
    """Amendment 1, rule 2b: Fellegi-Sunter weights and prior by expectation maximisation over the scored pairs,
    started from the label-trained values. Returns a model like fit_pairs' with new posteriors."""
    feats, levels = model["feats"], model["levels"]
    m = [np.array(w["m"]) for w in model["weights"]]
    u = [np.array(w["u"]) for w in model["weights"]]
    pi = model["prior"]
    # Work on distinct feature patterns: same posterior for every pair with the same pattern.
    code = np.zeros(len(feats), dtype=np.int64)
    for j, L in enumerate(levels):
        code = code * L + feats[:, j]
    pats, inv, cnt = np.unique(code, return_inverse=True, return_counts=True)
    pf = feats[np.unique(code, return_index=True)[1]]
    cnt = cnt.astype(float)
    ll_old, it = -np.inf, 0
    for it in range(1, max_iter + 1):
        lm = np.log(pi) + sum(np.log(m[j][pf[:, j]]) for j in range(len(levels)))
        lu = np.log(1 - pi) + sum(np.log(u[j][pf[:, j]]) for j in range(len(levels)))
        mx = np.maximum(lm, lu)
        ll = float((cnt * (mx + np.log(np.exp(lm - mx) + np.exp(lu - mx)))).sum())
        g = 1.0 / (1.0 + np.exp(lu - lm))
        if ll - ll_old < tol and it > 1:
            break
        ll_old = ll
        wm, wu = cnt * g, cnt * (1 - g)
        pi = float(np.clip(wm.sum() / cnt.sum(), 1e-6, 1 - 1e-6))
        for j, L in enumerate(levels):
            m[j] = (np.bincount(pf[:, j], weights=wm, minlength=L) + 1e-3) / (wm.sum() + 1e-3 * L)
            u[j] = (np.bincount(pf[:, j], weights=wu, minlength=L) + 1e-3) / (wu.sum() + 1e-3 * L)
    lm = np.log(pi) + sum(np.log(m[j][pf[:, j]]) for j in range(len(levels)))
    lu = np.log(1 - pi) + sum(np.log(u[j][pf[:, j]]) for j in range(len(levels)))
    post = (1.0 / (1.0 + np.exp(lu - lm)))[inv.reshape(-1)]
    out = dict(model)
    out.update({"post": post, "prior": pi, "weights": [{"m": m[j].tolist(), "u": u[j].tolist()} for j in
                                                         range(len(levels))], "em_iterations": it})
    return out


def link(det: np.ndarray, model: dict, threshold: float) -> np.ndarray:
    """Rule 2: deterministic users joined by every scored pair at or above the threshold."""
    keep = model["post"] >= threshold
    nu = int(det.max()) + 1 if len(det) else 0
    lab = components(nu, det[model["a"][keep]], det[model["b"][keep]])
    return lab[det]


def band_draws(det: np.ndarray, model: dict, k: int, rng: np.random.Generator):
    """Rule 3: k linkings, each scored pair linked independently with its posterior."""
    nu = int(det.max()) + 1 if len(det) else 0
    live = model["post"] >= 0.01
    pa, pb, pp = det[model["a"][live]], det[model["b"][live]], model["post"][live]
    for _ in range(k):
        keep = rng.random(len(pp)) < pp
        lab = components(nu, pa[keep], pb[keep])
        yield lab[det]
