import sys, re, json
sys.path.insert(0, '.')
from partitions_gf import SPECS, G_of, q
import batch
from sympy import symbols, cancel, together, Poly, expand, fraction, series
from sympy.parsing.sympy_parser import parse_expr, standard_transformations, implicit_multiplication_application, convert_xor
x = symbols('x'); TR = standard_transformations + (implicit_multiplication_application, convert_xor)
def block(aid):
    t = open(f'/home/user/oeisdata/seq/{aid[:4]}/{aid}.seq').read()
    m = re.search(rf'%F {aid} Conjectures? from _Colin Barker_[^\n]*\(Start\)\n(.*?)%F {aid} \(End\)', t, re.S)
    if m: return [re.sub(rf'^%F {aid} ', '', l) for l in m.group(1).strip().split('\n')]
    return [re.sub(rf'^%F {aid} ', '', l) for l in t.split('\n') if 'Colin Barker' in l and 'onjecture' in l]
out = []
for aid in SPECS:
    k, d, w = SPECS[aid]; G = G_of(k, d, w)
    terms, off, _ = batch.oeis(aid)
    res = {'id': aid, 'claims': []}
    for line in block(aid):
        line = re.sub(r'Conjectures? from _Colin Barker_, \w+ \d+ \d+: ', '', line)
        line = re.split(r' - _', line)[0]
        if line.startswith('G.f.:'):
            g = parse_expr(line[5:].strip().rstrip('.').replace('x', '(x)'), local_dict={'x': x}, transformations=TR)
            ok = cancel(together(g.subs(x, q) - G)) == 0
            res['claims'].append({'type': 'g.f.', 'verdict': 'TRUE (identical to exact g.f.)' if ok else 'FALSE (differs from exact g.f.)'})
        m = re.match(r'a\(n\) = (.*?) for n\s*>\s*(\d+)', line)
        if m and 'a(n-1)' in m.group(1):
            rhs = m.group(1); N = int(m.group(2))
            coef = {}
            e = parse_expr(re.sub(r'a\(n-(\d+)\)', r'A\1', rhs).replace('^','**'))
            R = 1
            for j in range(1, 40):
                c = e.coeff(symbols('A%d' % j))
                if c != 0: R -= c*q**j
            RG = cancel(together(R*G))
            num, den = fraction(RG)
            if den.free_symbols:
                res['claims'].append({'type': 'recurrence', 'verdict': 'FALSE (R*G not polynomial: fails infinitely often)'})
            else:
                P = Poly(expand(RG), q); order = Poly(R, q).degree()
                fails = [nn for nn in range(order, P.degree() + 1) if P.coeff_monomial(q**nn) != 0 and nn >= off]
                bad = [nn for nn in fails if nn > N]
                res['claims'].append({'type': 'recurrence for n>%d' % N, 'failures_any_n': fails,
                                      'verdict': 'TRUE as stated' if not bad else 'FALSE at n=%s (inside stated range)' % bad})
    out.append(res); print(json.dumps(res), flush=True)
