"""2kwas: independent transfer-matrix engine and brute-force enumerator for the Hardin tables (iis:2611.00306 review).

Written from the OEIS definitions only; it does not use or import the authors' modules.

Orientation.  The original array has n rows and k columns.  A column-k sequence (k fixed, n growing) is computed
in "col" mode: engine rows = original rows, engine width w = k.  A row-n sequence (n fixed, k growing) is computed
in "row" mode on the transpose: engine row i = original column i, engine width w = n, and an engine offset (a, b)
is the original offset (b, a).  The upper-left cell is (0, 0) in both.

Local rules.  State after placing engine row i = (row i-1 or ABSENT, row i, number of violations so far).  Placing
row i+1 completes the neighbourhood of row i, whose violations are then counted.  The last row is completed by ABSENT.
"""
import itertools
import numpy as np
from hardin_specs import spec_for  # noqa: F401  (re-exported for scripts)


def bits(x, w):
    return [(x >> j) & 1 for j in range(w)]


# ---------------------------------------------------------------- local rules: violation table of the middle row
def viol_table(spec, w, mode):
    """viol[u][c][d] = number of violating cells in engine row c with row u above and d below; index 2**w = ABSENT"""
    R = 1 << w
    NA = R
    us = np.arange(R + 1)
    U, C, Dn = np.meshgrid(us, np.arange(R), us, indexing="ij")
    U = U.ravel(); C = C.ravel(); Dn = Dn.ravel()
    rows = {}
    for name, X in (("u", U), ("c", C), ("d", Dn)):
        present = X != NA
        vals = np.stack([((X >> j) & 1) for j in range(w)], axis=1)
        vals[~present] = 0
        rows[name] = (present, vals)
    total = np.zeros(U.shape, dtype=np.int64)
    for j in range(w):
        v = rows["c"][1][:, j]
        nb = {}
        for o in spec["nbhd"]:
            a, b = (o if mode == "col" else (o[1], o[0]))   # engine offset of the original offset o
            jj = j + b
            if jj < 0 or jj >= w:
                nb[o] = (np.zeros(U.shape, dtype=bool), np.zeros(U.shape, dtype=np.int64)); continue
            src = {-1: "u", 0: "c", 1: "d"}[a]
            pres, vals = rows[src]
            nb[o] = (pres.copy(), vals[:, jj].astype(np.int64))
        ok = spec["ok"](v.astype(np.int64), nb)
        total += (~ok).astype(np.int64)
    return total.reshape(R + 1, R, R + 1)


class LocalEngine:
    def __init__(self, spec, w, mode):
        self.spec, self.w, self.mode = spec, w, mode
        self.R = 1 << w
        self.NA = self.R
        self.e = spec["exc"] if spec["exc"] is not None else 0
        self.vt = viol_table(spec, w, mode).tolist()
        self.ulz = spec["ulz"]

    def start(self):
        st = {}
        for r in range(self.R):
            if self.ulz and (r & 1):
                continue
            st[(self.NA, r, 0)] = 1
        return st

    def step(self, st):
        new = {}
        vt, e, R = self.vt, self.e, self.R
        for (u, c, cnt), x in st.items():
            row = vt[u][c]
            for d in range(R):
                c2 = cnt + row[d]
                if c2 <= e:
                    key = (c, d, c2)
                    new[key] = new.get(key, 0) + x
        return new

    def final(self, st):
        vt, e, NA = self.vt, self.e, self.NA
        return sum(x for (u, c, cnt), x in st.items() if cnt + vt[u][c][NA] == e)

    def live_states(self):
        """|reachable from the start states  intersect  co-reachable to an accepting state|"""
        vt, e, R, NA = self.vt, self.e, self.R, self.NA
        succ = {}
        reach = set(self.start())
        frontier = list(reach)
        while frontier:
            s = frontier.pop()
            u, c, cnt = s
            out = []
            for d in range(R):
                c2 = cnt + vt[u][c][d]
                if c2 <= e:
                    out.append((c, d, c2))
            succ[s] = out
            for t in out:
                if t not in reach:
                    reach.add(t); frontier.append(t)
        acc = {s for s in reach if s[2] + vt[s[0]][s[1]][NA] == e}
        pred = {s: [] for s in reach}
        for s, out in succ.items():
            for t in out:
                pred[t].append(s)
        co = set(acc); frontier = list(acc)
        while frontier:
            t = frontier.pop()
            for s in pred[t]:
                if s not in co:
                    co.add(s); frontier.append(s)
        return len(reach & co)

    def sequence(self, nmax):
        st = self.start()
        out = [self.final(st)]
        for _ in range(nmax - 1):
            st = self.step(st)
            out.append(self.final(st))
        return out


# ---------------------------------------------------------------- repeated-value rules (A267xxx)
def cond_ok(cond, prev, cur):
    if cond == "neq": return cur != prev
    if cond == "eq": return cur == prev
    if cond == "gt": return cur > prev
    if cond == "ge": return cur >= prev
    raise ValueError(cond)


def line_ok(seq, cond):
    """a line read in order: a repeated value is an element equal to its predecessor; each repeated value is
    compared with the previous repeated value of the same line"""
    last_rep = None
    for i in range(1, len(seq)):
        if seq[i] == seq[i - 1]:
            if last_rep is not None and not cond_ok(cond, last_rep, seq[i]):
                return False
            last_rep = seq[i]
    return True


class RepeatEngine:
    """engine rows are lines of type 'along' (original rows in col mode, original columns in row mode);
    engine columns are lines of type 'across'"""
    def __init__(self, spec, w, mode):
        self.spec, self.w, self.mode = spec, w, mode
        self.R = 1 << w
        self.along = spec["rowcond"] if mode == "col" else spec["colcond"]
        self.across = spec["colcond"] if mode == "col" else spec["rowcond"]
        self.rowok = [line_ok(bits(r, w), self.along) for r in range(self.R)]
        self.ulz = spec["ulz"]

    def start(self):
        st = {}
        for r in range(self.R):
            if self.ulz and (r & 1):
                continue
            if not self.rowok[r]:
                continue
            key = tuple((b, None) for b in bits(r, self.w))   # per engine column: (last value, last repeated value)
            st[key] = st.get(key, 0) + 1
        return st

    def advance(self, key, r):
        out = []
        for (last, rep), b in zip(key, bits(r, self.w)):
            if b == last:
                if rep is not None and not cond_ok(self.across, rep, b):
                    return None
                rep = b
            out.append((b, rep))
        return tuple(out)

    def step(self, st):
        new = {}
        for key, x in st.items():
            for r in range(self.R):
                if not self.rowok[r]:
                    continue
                k2 = self.advance(key, r)
                if k2 is not None:
                    new[k2] = new.get(k2, 0) + x
        return new

    def final(self, st):
        return sum(st.values())

    def live_states(self):
        reach = set(self.start()); frontier = list(reach)
        while frontier:
            s = frontier.pop()
            for r in range(self.R):
                if self.rowok[r]:
                    t = self.advance(s, r)
                    if t is not None and t not in reach:
                        reach.add(t); frontier.append(t)
        return len(reach)   # every state is accepting

    def sequence(self, nmax):
        st = self.start()
        out = [self.final(st)]
        for _ in range(nmax - 1):
            st = self.step(st)
            out.append(self.final(st))
        return out


def engine(spec, w, mode):
    return LocalEngine(spec, w, mode) if spec["kind"] == "local" else RepeatEngine(spec, w, mode)


def T(spec, n, k):
    """T(n,k) through the engine along the shorter side"""
    if k <= n:
        return engine(spec, k, "col").sequence(n)[-1]
    return engine(spec, n, "row").sequence(k)[-1]


# ---------------------------------------------------------------- literal enumeration of finished arrays
def brute(spec, n, k):
    M = 1 << (n * k)
    idx = np.arange(M, dtype=np.int64)
    A = np.stack([((idx >> (i * k + j)) & 1) for i in range(n) for j in range(k)], axis=1).reshape(M, n, k)
    if spec["ulz"]:
        A = A[A[:, 0, 0] == 0]
    if spec["kind"] == "repeat":
        cnt = 0
        for arr in A:
            if all(line_ok(list(arr[i, :]), spec["rowcond"]) for i in range(n)) and \
               all(line_ok(list(arr[:, j]), spec["colcond"]) for j in range(k)):
                cnt += 1
        return cnt
    nviol = np.zeros(A.shape[0], dtype=np.int64)
    for i in range(n):
        for j in range(k):
            v = A[:, i, j].astype(np.int64)
            nb = {}
            for (dr, dc) in spec["nbhd"]:
                ii, jj = i + dr, j + dc
                if 0 <= ii < n and 0 <= jj < k:
                    nb[(dr, dc)] = (np.ones(A.shape[0], dtype=bool), A[:, ii, jj].astype(np.int64))
                else:
                    nb[(dr, dc)] = (np.zeros(A.shape[0], dtype=bool), np.zeros(A.shape[0], dtype=np.int64))
            nviol += (~spec["ok"](v, nb)).astype(np.int64)
    e = spec["exc"] if spec["exc"] is not None else 0
    return int((nviol == e).sum())
