"""Decide OEIS recurrence conjectures for sequences with an explicit closed-form term
a(n) built from binomials, factorials and powers (finite sums of such).
TRUE  : the instance  L(n) = sum_j P_j(n) a(n-j) + rest(n)  simplifies to 0 symbolically
        (gamma form, valid for n >= n0 where all binomial/factorial arguments are generic),
        and every instance n < n0 + 5 is checked on the exact OEIS terms.
FALSE : an explicit instance on the exact OEIS terms is nonzero (a counterexample)."""
import sys, re, json
sys.path.insert(0, '/home/user/oeisproofs')
import batch
from sympy import (symbols, binomial, factorial, gamma, gammasimp, combsimp, simplify, expand,
                   expand_func, Rational, catalan, S, Integer, nsimplify)
from sympy.parsing.sympy_parser import (parse_expr, standard_transformations,
                                        implicit_multiplication_application, convert_xor)
n = symbols('n', integer=True)
TR = standard_transformations + (implicit_multiplication_application, convert_xor)

def parse_closed(s):
    s = re.split(r' - _|\. - |\(End\)', s)[0].strip().rstrip('.')
    s = s.split('=', 1)[1] if s.startswith('a(n)') else s
    if '=' in s:
        s = s.split('=')[0]
    s = re.sub(r'\bC\(', 'binomial(', s)
    s = s.replace('Catalan(', 'catalan(')
    return parse_expr(s, local_dict={'n': n, 'binomial': binomial, 'factorial': factorial,
                                     'catalan': catalan}, transformations=TR)

def val(e, k):
    v = e.subs(n, k)
    v = v.rewrite(binomial) if False else v
    return Integer(v) if v.is_Integer else nsimplify(v)

def decide(aid, expr_str):
    terms, off, conjs = batch.oeis(aid)
    a = parse_closed(expr_str)
    calc = [a.subs(n, off + i) for i in range(len(terms))]
    match = all(calc[i] == terms[i] for i in range(len(terms)))
    out = {'id': aid, 'closed_form': str(a), 'terms_match': match, 'n_terms': len(terms), 'results': []}
    if not match:
        bad = [off + i for i in range(len(terms)) if calc[i] != terms[i]]
        out['mismatch_at'] = bad[:6]
        return out
    for txt in conjs:
        try:
            Ps, rest = batch.parse_rec(txt)
        except Exception as ex:
            out['results'].append({'skip': 'parse'}); continue
        N_ = symbols('n')
        Ps = [P.subs(N_, n) for P in Ps]; rest = rest.subs(N_, n)
        r = len(Ps) - 1
        inst = lambda k: sum(Ps[j].subs(n, k)*terms[k - j - off] for j in range(r + 1)
                             if k - j - off >= 0) + rest.subs(n, k) if all(k - j - off >= 0 for j in range(r + 1)) else None
        num_bad = [k for k in range(off + r, off + len(terms)) if inst(k) not in (None, 0)]
        res = {'order': r, 'numeric_failures': num_bad}
        L = sum(Ps[j]*a.subs(n, n - j) for j in range(r + 1)) + rest
        Lg = gammasimp(expand_func(L.rewrite(gamma)))
        Lg = simplify(Lg)
        res['symbolic_zero'] = (Lg == 0)
        if num_bad and len(num_bad) > 3:
            res['verdict'] = 'FALSE (counterexamples at n=%s...)' % num_bad[:4]
        elif Lg == 0:
            res['verdict'] = 'TRUE for n>=%d' % (off + r) if not num_bad else 'TRUE for n>%d; FALSE at n=%s' % (max(num_bad), num_bad)
        else:
            res['verdict'] = 'UNDECIDED (symbolic form not reduced: %s)' % str(Lg)[:80] if not num_bad else 'FALSE at n=%s; symbolic undecided' % num_bad
        out['results'].append(res)
    return out

if __name__ == '__main__':
    for line in open(sys.argv[1]):
        aid, s = line.split(' ', 1)
        try:
            o = decide(aid, s.strip())
        except Exception as ex:
            o = {'id': aid, 'error': repr(ex)[:160]}
        print(json.dumps(o, default=str), flush=True)
