"""Graph features (DESIGN.md, "Arms" and "Linking rules"). No edge crosses time steps, so every feature computed on the
whole graph is a feature computed inside the transaction's own step."""
from __future__ import annotations

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


class Adj:
    def __init__(self, n: int, src: np.ndarray, dst: np.ndarray):
        ones = np.ones(len(src), dtype=np.float64)
        self.n = n
        self.out = sp.csr_matrix((ones, (src, dst)), shape=(n, n))      # row i: children of i
        self.inn = self.out.T.tocsr()                                    # row i: parents of i
        und = (self.out + self.inn).tocsr()
        und.data[:] = 1.0
        self.und = und
        two = (und @ und).tocsr()
        reach = (und + two).tocsr()
        reach.data[:] = 1.0
        reach.setdiag(0)
        reach.eliminate_zeros()
        self.reach2 = reach                                              # distinct transactions within two hops
        gp = (self.inn @ self.inn).tocsr()
        gp.data[:] = 1.0
        self.grandparents = gp
        self.comp_n, self.comp = connected_components(und, directed=False)

    def indeg(self):
        return np.asarray(self.inn.sum(axis=1)).ravel()

    def outdeg(self):
        return np.asarray(self.out.sum(axis=1)).ravel()

    def deg(self):
        return np.asarray(self.und.sum(axis=1)).ravel()


def _mean_max(m: sp.csr_matrix, v: np.ndarray):
    """Mean and maximum of v over each row's neighbours; NaN where a row has none."""
    cnt = np.diff(m.indptr)
    s = m @ v
    mean = np.where(cnt > 0, s / np.maximum(cnt, 1), np.nan)
    mx = np.full(m.shape[0], np.nan)
    has = np.flatnonzero(cnt)
    if len(has):
        vals = v[m.indices]
        mx[has] = np.maximum.reduceat(vals, m.indptr[has])
    return mean, mx


def structure(a: Adj) -> np.ndarray:
    """A1: in-degree, out-degree, total degree, two-hop reach, component size, neighbours' mean and max degree."""
    deg = a.deg()
    comp_size = np.bincount(a.comp)[a.comp]
    nmean, nmax = _mean_max(a.und, deg)
    reach = np.diff(a.reach2.indptr)
    return np.column_stack([a.indeg(), a.outdeg(), deg, reach, comp_size, nmean, nmax])


def broadcast_structure(a: Adj) -> np.ndarray:
    """A1rt: only what exists when the transaction is broadcast: in-degree and distinct grandparents."""
    return np.column_stack([a.indeg(), np.diff(a.grandparents.indptr)])


def propagation(a: Adj, score: np.ndarray, threshold: float) -> np.ndarray:
    """A4: parents', children's and two-hop mean and max first-stage score; neighbours above the threshold; flags."""
    pm, px = _mean_max(a.inn, score)
    cm, cx = _mean_max(a.out, score)
    tm, tx = _mean_max(a.reach2, score)
    above = a.und @ (score > threshold).astype(np.float64)
    return np.column_stack([pm, px, cm, cx, tm, tx, above,
                            (np.diff(a.inn.indptr) > 0).astype(float), (np.diff(a.out.indptr) > 0).astype(float)])


def label_counts(a: Adj, known: np.ndarray) -> np.ndarray:
    """A3 two-pass (and A3 strict): counts from labels known at scoring time. known: 1 illicit, 0 licit, -1 not known.
    Confirmed-illicit parents, confirmed-illicit children, confirmed-licit neighbours, reviewed neighbours,
    confirmed-illicit transactions within two hops."""
    ill = (known == 1).astype(np.float64)
    lic = (known == 0).astype(np.float64)
    rev = (known >= 0).astype(np.float64)
    return np.column_stack([a.inn @ ill, a.out @ ill, a.und @ lic, a.und @ rev, a.reach2 @ ill])


def true_label_counts(a: Adj, label: np.ndarray) -> np.ndarray:
    """F2 (planted fault): one-hop counts of neighbours' true labels, including labels nobody has at scoring time."""
    return np.column_stack([a.und @ (label == 1).astype(np.float64), a.und @ (label == 0).astype(np.float64)])


def clusters(a: Adj, seeds: np.ndarray, hops: int):
    """R1 (hops=1) or R2 (hops=2): attribute every transaction within `hops` of a seed. Returns the attributed mask
    (seeds excluded) and a cluster id per member (-1 outside), where overlapping neighbourhoods merge."""
    m = a.und if hops == 1 else a.reach2
    seed_mask = np.zeros(a.n, bool)
    seed_mask[seeds] = True
    attributed = np.asarray((m[seeds].sum(axis=0) > 0)).ravel() & ~seed_mask
    members = seed_mask | attributed
    # merge: link each seed to its attributed transactions, then take components over the members
    rows = m[seeds].tocoo()
    s_idx = seeds[rows.row]
    t_idx = rows.col
    keep = members[t_idx]
    link = sp.csr_matrix((np.ones(int(keep.sum())), (s_idx[keep], t_idx[keep])), shape=(a.n, a.n))
    link = (link + link.T).tocsr()
    _, comp = connected_components(link, directed=False)
    cid = np.where(members, comp, -1)
    return attributed, cid
