"""2kwas: readings of the 280 Hardin table definitions (iis:2611.00306 review), written from the OEIS names.

A local spec is a dict:
  kind = "local"
  nbhd = list of original offsets (dr, dc)
  ok(v, nb) -> boolean numpy array: does the cell satisfy the rule?  v = cell values, nb[o] = (present, value)
  exc = None (every cell must satisfy) or e (exactly e cells violate)
  ulz = True if the upper-left element must be 0
A repeat spec (A267xxx) is a dict with kind = "repeat", rowcond, colcond in {"neq", "eq", "gt", "ge"}, ulz.
"""
import re
import numpy as np

W = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}

H = [(0, -1), (0, 1)]
V = [(-1, 0), (1, 0)]
D = [(-1, -1), (1, 1)]          # diagonal: NW-SE
A = [(-1, 1), (1, -1)]          # antidiagonal: NE-SW
KING = H + V + D + A

NB = {
    "king-move": KING,
    "horizontally, vertically or antidiagonally": H + V + A,
    "horizontally or vertically": H + V,
    "horizontal and vertical": H + V,
    "horizontal, vertical and antidiagonal": H + V + A,
    "horizontal and antidiagonal": H + A,
    "horizontal, diagonal or antidiagonal": H + D + A,
    "horizontal, diagonal and antidiagonal": H + D + A,
}


def counts(v, nb, offs):
    """number of present neighbours among offs, and number of those equal to v"""
    tot = 0
    eq = 0
    for o in offs:
        pres, val = nb[o]
        tot = tot + pres.astype(np.int64)
        eq = eq + (pres & (val == v)).astype(np.int64)
    return tot, eq


def parse_set(s):
    return {int(x) for x in re.findall(r"\d+", s)}


def spec_for(aid, name):
    t = name.replace("T(n,k)=Number of nXk 0..1 arrays ", "").strip()

    # F1: every element unequal to S <nb> adjacent elements[, with upper left element zero].
    m = re.fullmatch(r"with every element unequal to ([\d, or]+?) (king-move|horizontally, vertically or antidiagonally|"
                     r"horizontally or vertically) adjacent elements(, with upper left element zero)?\.", t)
    if m:
        S = parse_set(m.group(1)); offs = NB[m.group(2)]
        def ok(v, nb, S=S, offs=offs):
            tot, eq = counts(v, nb, offs)
            return np.isin(tot - eq, list(S))
        return dict(kind="local", nbhd=offs, ok=ok, exc=None, ulz=bool(m.group(3)), family="F1 unequal-count in S")

    # F2: every element equal to S king-move adjacent elements, with upper left element zero.
    m = re.fullmatch(r"with every element equal to ([\d, or]+?) king-move adjacent elements, with upper left element zero\.", t)
    if m:
        S = parse_set(m.group(1)); offs = KING
        def ok(v, nb, S=S, offs=offs):
            tot, eq = counts(v, nb, offs)
            return np.isin(eq, list(S))
        return dict(kind="local", nbhd=offs, ok=ok, exc=None, ulz=True, family="F2 equal-count in S")

    # F3: no element equal to more than m of its <nb> neighbors[, with the exception of exactly e element(s)],? and with new values ...
    m = re.fullmatch(r"with no element equal to more than (one|two|three|four) of its (.+?) neighbors"
                     r"(?:, with the exception of exactly (one|two) elements?)?,? and with new values introduced in order 0 "
                     r"sequentially upwards\.", t)
    if m:
        mm = W[m.group(1)]; offs = NB[m.group(2)]; e = W[m.group(3)] if m.group(3) else None
        def ok(v, nb, mm=mm, offs=offs):
            tot, eq = counts(v, nb, offs)
            return eq <= mm
        return dict(kind="local", nbhd=offs, ok=ok, exc=e, ulz=True, family="F3 equal-count <= m")

    # F4: no 1 equal to more than m of its <nb> neighbors[, with the exception of exactly e element(s)].
    m = re.fullmatch(r"with no 1 equal to more than (one|two|three|four) of its (.+?) neighbors"
                     r"(?:, with the exception of exactly (one|two) elements?)?\.", t)
    if m:
        mm = W[m.group(1)]; offs = NB[m.group(2)]; e = W[m.group(3)] if m.group(3) else None
        def ok(v, nb, mm=mm, offs=offs):
            tot, eq = counts(v, nb, offs)
            return (v == 0) | (eq <= mm)
        return dict(kind="local", nbhd=offs, ok=ok, exc=e, ulz=False, family="F4 no 1 with equal-count > m")

    # F5: no element equal to a strict majority of its <nb> neighbors[, with the exception of exactly e element(s)],? [and ]with new values ...
    m = re.fullmatch(r"with no element equal to a strict majority of its (.+?) neighbors"
                     r"(?:, with the exception of exactly (one|two) elements?)?,? (?:and )?with new values introduced in order 0 "
                     r"sequentially upwards\.", t)
    if m:
        offs = NB[m.group(1)]; e = W[m.group(2)] if m.group(2) else None
        def ok(v, nb, offs=offs):
            tot, eq = counts(v, nb, offs)
            return ~(2 * eq > tot)
        return dict(kind="local", nbhd=offs, ok=ok, exc=e, ulz=True, family="F5 no strict majority")

    # F9: no 1 adjacent to j king-move neighboring 1(s).
    m = re.fullmatch(r"with no 1 adjacent to (\d) king-move neighboring 1s?\.", t)
    if m:
        j = int(m.group(1))
        def ok(v, nb, j=j):
            tot, eq = counts(v, nb, KING)
            return (v == 0) | (eq != j)
        return dict(kind="local", nbhd=KING, ok=ok, exc=None, ulz=False, family="F9 no 1 with exactly j neighbouring 1s")

    # F6: the six A240xxx tables (new values 0..1 introduced in row major order = upper left element 0)
    a240 = {
        "A240484": ("no element equal to more than two horizontal or vertical neighbors", lambda eh, ev: eh + ev <= 2),
        "A240519": ("no element equal to exactly two horizontal and vertical neighbors", lambda eh, ev: eh + ev != 2),
        "A240636": ("no element equal to exactly three horizontal or vertical neighbors", lambda eh, ev: eh + ev != 3),
        "A240649": ("no element equal to the same number of vertical neighbors as horizontal neighbors", lambda eh, ev: ev != eh),
        "A240656": ("no element equal to exactly one horizontal or vertical neighbor", lambda eh, ev: eh + ev != 1),
        "A240783": ("no element equal to fewer vertical neighbors than horizontal neighbors", lambda eh, ev: ~(ev < eh)),
    }
    if aid in a240:
        phrase, f = a240[aid]
        assert t == "with " + phrase + ", with new values 0..1 introduced in row major order.", (aid, t)
        def ok(v, nb, f=f):
            _, eh = counts(v, nb, H)
            _, ev = counts(v, nb, V)
            return np.asarray(f(eh, ev), dtype=bool)
        return dict(kind="local", nbhd=H + V, ok=ok, exc=None, ulz=True, family="F6 A240xxx h/v counts")

    # F7: A208637
    if aid == "A208637":
        assert t == ("with new values 0..1 introduced in row major order and no element equal to more than one of its "
                     "immediate leftward or upward or right-upward antidiagonal neighbors."), t
        offs = [(0, -1), (-1, 0), (-1, 1)]
        def ok(v, nb, offs=offs):
            tot, eq = counts(v, nb, offs)
            return eq <= 1
        return dict(kind="local", nbhd=offs, ok=ok, exc=None, ulz=True, family="F7 one-sided neighbourhood")

    # F8: repeated values
    rep = {
        "A267644": ("with every repeated value in every row and column unequal to the previous repeated value, and new values "
                    "introduced in row-major sequential order.", "neq", "neq", True),
        "A267667": ("with every repeated value in every row unequal to the previous repeated value, and in every column equal to "
                    "the previous repeated value, and new values introduced in row-major sequential order.", "neq", "eq", True),
        "A267719": ("with every repeated value in every row and column greater than the previous repeated value.", "gt", "gt", False),
        "A267735": ("with every repeated value in every row and column greater than or equal to the previous repeated value.",
                    "ge", "ge", False),
        "A267788": ("with every repeated value in every row greater than or equal to, and in every column greater than, the "
                    "previous repeated value.", "ge", "gt", False),
    }
    if aid in rep:
        phrase, rc, cc, ulz = rep[aid]
        assert t == phrase, (aid, t)
        return dict(kind="repeat", rowcond=rc, colcond=cc, ulz=ulz, family="F8 repeated values")

    raise ValueError("no reading for %s: %s" % (aid, t))
