"""Harness for fixed-width array sequences.  A module arrays/<A-id>.py must define
  M  : square matrix (list of lists of ints)   -- transfer matrix built from the rule
  u, v : integer vectors                       -- so that a(n) = u . M^(n-n0) . v for n >= n0
  n0 : int
  initial : dict {n: a(n)} for offset <= n < n0 (may be empty)
  brute(n) : independent direct enumeration of the arrays (used for small n only)
Checks: (1) brute(n) == transfer value == OEIS term for small n; (2) transfer values == all
OEIS terms; (3) each Barker recurrence 'a(n) = sum c_j a(n-j) for n>N' is decided EXACTLY:
b(n) = a(n) - sum c_j a(n-j) satisfies the characteristic recurrence of M (order d) for
n >= n0 + r, so b == 0 there iff it vanishes at d consecutive n; smaller n are checked directly.
Barker's g.f. is checked by: its coefficients satisfy its own denominator recurrence (order e),
so g.f. == a iff they agree on n < offset + d + e + (numerator degree) + 2."""
import sys, re, json, importlib.util
sys.path.insert(0, '/home/user/oeisproofs')
import batch
from sympy import symbols, Rational, series, parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application, convert_xor
x = symbols('x')
TR = standard_transformations + (implicit_multiplication_application, convert_xor)

def matvec(M, v):
    return [sum(M[i][j]*v[j] for j in range(len(v))) for i in range(len(M))]

def values(mod, upto, off):
    vals = {}
    w = list(mod.v)
    for k in range(off, upto):
        if k < mod.n0:
            vals[k] = mod.initial[k]
        else:
            if k > mod.n0:
                w = matvec(mod.M, w)
            vals[k] = sum(a*b for a, b in zip(mod.u, w))
    return vals

def barker(aid):
    t = open(f'/home/user/oeisdata/seq/{aid[:4]}/{aid}.seq').read()
    lines = []
    m = re.search(rf'%F {aid} Conjectures? from _Colin Barker_[^\n]*\(Start\)\n(.*?)\(End\)', t, re.S)
    if m:
        lines = [re.sub(rf'^%F {aid} ', '', l) for l in m.group(1).strip().split('\n')]
    lines += [re.sub(rf'^%F {aid} ', '', l) for l in t.split('\n') if 'Colin Barker' in l and 'onjecture' in l and 'Start' not in l]
    lines += [re.sub(rf'^%F {aid} ', '', l) for l in t.split('\n') if re.match(rf'^%F {aid} Empirical( for [^:]*)?: a\(n\) = .*a\(n-\d+\)', l)]
    return lines

def check(aid):
    spec = importlib.util.spec_from_file_location(aid, f'/home/user/oeisproofs/arrays/{aid}.py')
    mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
    terms, off, _ = batch.oeis(aid)
    d = len(mod.M)
    vals = values(mod, off + len(terms) + 3*d + 60, off)
    out = {'id': aid, 'states': d}
    out['oeis_match'] = all(vals[off + i] == terms[i] for i in range(len(terms)))
    bchk = []
    for k in range(off, off + 6):
        try:
            b = mod.brute(k)
        except Exception as ex:
            b = None
        if b is not None: bchk.append(b == vals[k])
    out['brute_match'] = bool(bchk) and all(bchk)
    out['brute_checked'] = len(bchk)
    claims = []
    for line in barker(aid):
      try:
          line = re.sub(r'Conjectures? from _Colin Barker_, \w+ \d+ \d+: ', '', line)
          line = re.split(r' - _', line)[0].strip()
          src = 'Hardin empirical' if line.startswith('Empirical') else 'Barker'
          if line.startswith('Empirical'):
              if re.match(r'Empirical for ', line):
                  continue   # column/row-specific empirical lines are not handled
              line = line.split(':', 1)[1].strip()
          mm = re.match(r'a\(n\) = (.*?)(?: for n\s*>\s*(\d+))?\.?\s*$', line)
          if mm and 'a(n-' in mm.group(1) and 'a(n+' not in mm.group(1):
              rhs, N = mm.group(1), (int(mm.group(2)) if mm.group(2) else -1)
              e = parse_expr(re.sub(r'a\(n-(\d+)\)', r'A\1', rhs).replace('^', '**'))
              cs = {j: e.coeff(symbols('A%d' % j)) for j in range(1, 60) if e.coeff(symbols('A%d' % j)) != 0}
              r = max(cs)
              def b(nn): return vals[nn] - sum(c*vals[nn - j] for j, c in cs.items())
              start = max(N + 1, off + r)
              # exact decision: b vanishes for all n >= max(start, n0 + r) iff it vanishes on d consecutive values there
              s2 = max(start, mod.n0 + r)
              ok_tail = all(b(nn) == 0 for nn in range(s2, s2 + d + 1))
              ok_head = all(b(nn) == 0 for nn in range(start, s2))
              fails_below = [nn for nn in range(off + r, start) if b(nn) != 0]
              if N < 0: N = off + r - 1
              claims.append({'type': '%s recurrence n>%d' % (src, N), 'verdict': 'TRUE as stated' if (ok_tail and ok_head) else 'FALSE',
                             'fails_below_stated_range': fails_below})
          if line.startswith('G.f.:'):
              g = parse_expr(line[5:].strip().rstrip('.'), local_dict={'x': x}, transformations=TR)
              from sympy import fraction, Poly, cancel
              P_, Q_ = fraction(cancel(g))
              e_ = Poly(Q_, x).degree(); p_ = Poly(P_, x).degree()
              L = max(off, mod.n0, p_ + 1) + d + e_ + 3
              s = series(g, x, 0, L).removeO()
              ok = all(s.coeff(x, k) == vals[k] for k in range(off, L)) and all(s.coeff(x, k) == 0 for k in range(0, off))
              claims.append({'type': 'g.f.', 'verdict': 'TRUE' if ok else 'FALSE', 'checked_to': L})
      except Exception as ex:
        claims.append({'type': 'unparsed line', 'line': line[:80], 'error': repr(ex)[:60]})
    out['claims'] = claims
    return out

if __name__ == '__main__':
    for aid in sys.argv[1:]:
        try:
            print(json.dumps(check(aid), default=str), flush=True)
        except Exception as ex:
            print(json.dumps({'id': aid, 'error': repr(ex)[:200]}), flush=True)
