"""Batch exact check of Mathar-style recurrence conjectures for sequences with
explicit algebraic o.g.f.  For each: parse recurrence -> P_j(n); compute
E(x) = sum_j x^j P_j(theta+j) A exactly; recurrence holds for all n where
[x^n]E = 0 (only n >= order are instances).  Terms are checked against the
OEIS %S data to guard against transcription/indexing errors."""
import re, sys, json
from sympy import (symbols, sqrt, Rational, series, simplify, radsimp, together,
                   Poly, expand, factor, cancel, nsimplify, S)
from sympy.parsing.sympy_parser import (parse_expr, standard_transformations,
                                        implicit_multiplication_application)
sys.path.insert(0, '/home/user/oeisproofs')
from ogf_check import E_of
x, n = symbols('x n')
TR = standard_transformations + (implicit_multiplication_application,)
SEQ = '/home/user/oeisdata/seq'

def oeis(aid):
    t = open(f'{SEQ}/{aid[:4]}/{aid}.seq').read()
    S_ = ''.join(re.findall(rf'^%[STU] {aid} (.*)$', t, re.M)).replace(' ', '')
    terms = [int(v) for v in S_.split(',') if v]
    off = int(re.search(rf'^%O {aid} (-?\d+)', t, re.M).group(1))
    conj = [l for l in re.findall(rf'^%F {aid} (Conjecture:.*)$', t, re.M) if 'a(n-1)' in l]
    return terms, off, conj

def parse_rec(text):
    s = text.split('Conjecture:')[1]
    s = re.split(r' - _|\. - |\(End\)', s)[0]
    s = s.replace('D-finite with recurrence', '').replace(':', '')
    s = re.split(r',\s*n\s*>', s)[0].strip().rstrip('.')
    lhs, rhs = s.split('=')
    expr_s = f'({lhs})-({rhs})'.replace('^', '**')
    expr_s = re.sub(r'a\(n\)', 'A0', expr_s)
    expr_s = re.sub(r'a\(n-(\d+)\)', lambda m: 'A' + m.group(1), expr_s)
    syms = {f'A{k}': symbols(f'A{k}') for k in range(0, 15)}
    syms['n'] = n
    e = expand(parse_expr(expr_s, local_dict=syms, transformations=TR))
    order = max(k for k in range(15) if e.coeff(syms[f'A{k}']) != 0)
    Ps = [e.coeff(syms[f'A{k}']) for k in range(order + 1)]
    rest = simplify(e - sum(Ps[k]*syms[f'A{k}'] for k in range(order + 1)))
    return Ps, rest

c = (1 - sqrt(1 - 4*x))/(2*x)           # Catalan g.f.
C = lambda z: ((1 - sqrt(1 - 4*z))/(2*z))
M = lambda z: (1 - z - sqrt(1 - 2*z - 3*z**2))/(2*z**2)   # Motzkin g.f.

GF = {
 'A157328': 1/(1 - 2*x*C(4*x)),
 'A155587': (1 + x*c)/(1 - x),
 'A166078': (3*(1 - x) - sqrt(1 + 6*x - 7*x**2))/(2*(1 - x)*(1 - 2*x)),
 'A166076': (7 + 5*x - sqrt(1 - 10*x - 7*x**2))/(2*(3 + 5*x + 2*x**2)),
 'A071715': (1 + x*c**4)*c**4,
 'A071264': (1 + x*c**4)*c**3,
 'A071722': (1 + x**2*c**2)*c**3,
 'A071717': (1 + x**2*c)*c**2,
 'A071719': (1 + x**2*c)*c**4,
 'A141222': -1/(2*x) + (2*x - 1)**2/(2*x*(1 - 4*x)**Rational(3, 2)),
 'A141771': c + 8*x**3/(sqrt(1 - 4*x)*(1 + sqrt(1 - 4*x))**3),
 'A114191': 1/(1 + x*C(-2*x)),
 'A114194': 1/(1 + x*(2 - x)*C(-2*x)),
 'A114121': (sqrt(1 - 4*x) + (1 - 2*x))/(2*(1 - 4*x)),
 'A114190': 1/(1 + x*(1 - x)*C(-2*x)),
 'A136304': (1 - x)**2*(1 - sqrt(1 - 4*x))/(2*x*(1 - 3*x + 2*x**2 - x**3)),
 'A128057': (1 + x)/sqrt(1 + 4*x**2),
 'A188314': (1/(1 - x))*C(x/((1 - x)*(1 - x**2))),
 'A188312': (1/(1 - x**2))*C(x/((1 - x)*(1 - x**2))),
 'A105695': (1 - x)*C(x/(1 + x)),
 'A105864': (1/(1 - x**2))*C(x/(1 - x**2)),
 'A105865': (1/(1 - 2*x**2))*C(x/(1 - 2*x**2)),
 'A240688': -(x*sqrt(-4*x**2 - 4*x + 1) - 2*x**2 - 3*x)/((x + 1)*sqrt(-4*x**2 - 4*x + 1) + 4*x**3 + 8*x**2 + 3*x - 1),
 'A116409': (1 - x - 2*x**2 + sqrt(1 - 2*x - 3*x**2))/(2*(1 - x)*(1 - 2*x - 3*x**2)),
 'A116387': 1/(sqrt(1 - 2*x - 3*x**2)*(2 - M(x))),
 'A116388': 1/((1 + x*(1 - M(x)))*sqrt(1 - 2*x - 3*x**2)),
 'A116406': ((1 + x - 2*x**2) + (1 + x)*sqrt(1 - 4*x**2))/(2*(1 - 4*x**2)),
 'A226316': Rational(1, 2) + 1/(1 + sqrt(1 - 8*x + 8*x**2)),
 'A135582': 1/((1 - x**2*c)*(1 - x - 2*x**2)),
 'A115967': 1/(2*sqrt(1 - 2*x - 3*x**2) - 1),
 'A132364': 1/(1 - x**2*c),
 'A132864': 1/(1 - 4*x*C(5*x)),
 'A097331': 1 + 2*x/(1 + sqrt(1 - 4*x**2)),
 'A182959': 2*(1 + x)**2/(1 - 2*x + sqrt(1 - 8*x)),
 'A162481': (1/(1 - x)**3)*C(x/(1 - x)**3),
 'A162477': (1/(1 - x)**2)*C(x/(1 - x)**4),
 'A162482': (1/(1 - x)**3)*M(x/(1 - x)**3),
 'A158196': (1 - x**2*c**4)/(1 - 3*x*c**2),
 'A158495': ((1 - 4*x) + sqrt(1 - 4*x))/(2*(1 - 2*x)),
 'A158197': (1 - x**2*c**4)/(1 - 4*x*c**2),
 'A108308': 1/(1 - x**2*C(2*x)),
 'A110521': 1/(1 - (x + x**2)*C(3*x)),
 'A025577': (x/(1 - x))*sqrt((1 + x)/(1 - 3*x)),
 'A179648': (1/(1 + 4*x - 2*x**2))*C(x/(1 + 4*x - 2*x**2)),
 'A165201': 1/(1 - x*c**3),
 'A165203': (1 + x)*c**3/(1 - x*c**3),
 'A127275': (sqrt(1 - 4*x) - x)/(1 - 4*x),
 'A139376': 1/((1 - x**2*c)*(1 - x - x**2)),
 'A104625': 1/(sqrt(1 - 4*x) - x**2),
 'A184120': (1/(1 + 4*x + 2*x**2))*C(x/(1 + 4*x + 2*x**2)),
 'A117186': (1 + x)*C(x**2)/((1 - x*C(x**2))*sqrt(1 - 4*x**2)),
 'A102882': (1 + 2*x)/sqrt((1 - 3*x**2)*(1 + 4*x + 5*x**2)),
 'A174107': (1/(1 - x + x**2))*C(x/(1 - x + x**2)),
 'A174783': (1 + 2*x - sqrt(1 - 4*x**2))/(2*(1 - x**2)*sqrt(1 - 4*x**2)),
 'A154623': 1 + (x/(1 - 5*x))*C(x/(1 - 5*x)),
}
for k in range(3, 11):
    aid = {3: 'A172025', 5: 'A172062', 6: 'A172063', 7: 'A172064', 8: 'A172065', 9: 'A172066', 10: 'A172067'}.get(k)
    if aid:
        GF[aid] = (2/(3*sqrt(1 - 4*x) - 1 + 4*x))*c**k

def run(aid, NT=30):
    A = GF[aid]
    terms, off, conjs = oeis(aid)
    s = series(A, x, 0, NT + off).removeO()
    a = {k: s.coeff(x, k) for k in range(0, NT + off)}
    calc = [a[k] for k in range(off, off + min(NT, len(terms)))]
    m = min(len(calc), len(terms))
    match = calc[:m] == terms[:m]
    out = {'id': aid, 'offset': off, 'terms_match_OEIS': match, 'checked_terms': m, 'results': []}
    if not match:
        out['calc'] = [str(v) for v in calc[:10]]; out['oeis'] = terms[:10]
        return out
    for txt in conjs:
        try:
            Ps, rest = parse_rec(txt)
        except Exception as ex:
            out['results'].append({'conj': txt[:200], 'error': 'parse: ' + str(ex)[:100]}); continue
        if rest != 0:
            out['results'].append({'conj': txt[:200], 'error': 'inhomogeneous/unparsed term: ' + str(rest)[:80]}); continue
        r = len(Ps) - 1
        E = simplify(radsimp(together(E_of(A, Ps))))
        Ep = factor(E)
        ispoly = bool(E.is_polynomial(x))
        bad_num = [k for k in range(max(r, off), NT + off - 1)
                   if sum(Ps[j].subs(n, k)*a.get(k - j, 0) for j in range(r + 1)) != 0]
        res = {'conj': txt[:200], 'order': r, 'E': str(Ep), 'E_is_polynomial': ispoly, 'numeric_failures': bad_num}
        if ispoly:
            deg = Poly(E, x).degree() if E != 0 else -1
            P = Poly(E, x) if E != 0 else None
            exact_fail = [k for k in range(r, deg + 1) if P is not None and P.coeff_monomial(x**k) != 0]
            res['exact_failures(n>=order)'] = exact_fail
            res['verdict'] = 'TRUE for all n>=%d' % r if not exact_fail else 'TRUE for n>%d; FALSE at n=%s' % (max(exact_fail), exact_fail)
        else:
            res['verdict'] = 'UNDECIDED (E not simplified to polynomial)'
        out['results'].append(res)
    return out

if __name__ == '__main__':
    ids = sys.argv[1:] or list(GF)
    for aid in ids:
        try:
            r = run(aid)
        except Exception as ex:
            r = {'id': aid, 'error': repr(ex)[:200]}
        print(json.dumps(r), flush=True)
