"""Batch 2: auto-translate OEIS 'G.f.:' / 'E.g.f.:' lines to SymPy and decide the
recurrence conjecture exactly.  A translation is only used if it reproduces the
OEIS terms; otherwise the entry is skipped (never guessed).

o.g.f.:  E = sum_j x^j P_j(theta+j) A,  instance n  <-> [x^n] E
e.g.f.:  E = sum_j P_j(theta+r) F^(r-j), instance n=m+r <-> [x^m/m!] E
Verdict only when E simplifies to a polynomial (exact); plus numeric agreement on
exact terms and a 60-digit random-point check of (E_raw - E_poly)."""
import re, sys, json, random
from sympy import (symbols, sqrt, Rational, series, simplify, radsimp, together, Poly, expand,
                   factor, exp, log, besseli, acos, asin, atan, sin, cos, cosh, sinh, tanh, tan,
                   factorial, diff, lambdify, Function, S, cancel)
from sympy.parsing.sympy_parser import (parse_expr, standard_transformations,
                                        implicit_multiplication_application, convert_xor)
import mpmath
sys.path.insert(0, '/home/user/oeisproofs')
import batch
x, n = symbols('x n')
TR = standard_transformations + (implicit_multiplication_application, convert_xor)
SEQ = '/home/user/oeisdata/seq'

def catalan_gf(z): return (1 - sqrt(1 - 4*z))/(2*z)
def motzkin_gf(z): return (1 - z - sqrt(1 - 2*z - 3*z**2))/(2*z**2)

SKIP = re.compile(r'satisf|reversion|continued|\.\.\.|int\(|Sum|sum\(|Product|prod|F\(|hypergeom|\bG\(|\bH\(|\bT\(|\bB\b|\bW\(|\bQ\(|\bU\(|where (?!c\(x\)|C\(x\)|M\(x\))|limit|Re\(|Im\(|floor|binomial', re.I)

def translate(line, aid):
    m = re.match(rf'^%F {aid} (E\.g\.f\.|G\.f\.|O\.g\.f\.|g\.f\.)\:?\s*(.*)$', line)
    if not m: return None
    kind = 'egf' if m.group(1).startswith('E') else 'ogf'
    s = m.group(2)
    s = re.split(r' - _|\s\[|\(End\)|\(conjectured\)', s)[0]
    s = re.split(r',?\s+where\s+', s)[0] if re.search(r'where\s+(c|C|M)\(x\)', s) else s
    s = re.split(r'\s+with\s+c\(x\)', s)[0]
    s = s.strip().rstrip('.;,').strip()
    s = re.sub(r'^[A-Za-z]\([xz]\)\s*=\s*', '', s)
    if '=' in s:
        s = s.split('=')[0].strip() if re.search(r'=\s*1/', s) is None else s.split('=')[0].strip()
    if SKIP.search(s) or not s: return None
    s = s.replace('[', '(').replace(']', ')').replace('{', '(').replace('}', ')')
    s = re.sub(r'\bz\b', 'x', s); s = re.sub(r'\bt\b', 'x', s)
    s = re.sub(r'Bessel_?I_?\(?\s*(\d)\s*,', r'besseli(\1,', s)
    s = re.sub(r'BesselI_(\d)\(', r'besseli(\1,', s)
    s = s.replace('arccos', 'acos').replace('arcsin', 'asin').replace('arctan', 'atan')
    loc = {'x': x, 'c': catalan_gf, 'C': catalan_gf, 'M': motzkin_gf, 'sqrt': sqrt, 'exp': exp,
           'log': log, 'besseli': besseli, 'acos': acos, 'asin': asin, 'atan': atan, 'sin': sin,
           'cos': cos, 'cosh': cosh, 'sinh': sinh, 'tanh': tanh, 'tan': tan, 'E': S.Exp1, 'Pi': S.Pi, 'pi': S.Pi}
    try:
        e = parse_expr(s, local_dict=loc, transformations=TR)
    except Exception:
        return None
    if e.free_symbols - {x}: return None
    return kind, e, s

def coeffs(e, kind, N):
    sr = series(e, x, 0, N).removeO()
    c = [sr.coeff(x, k) for k in range(N)]
    if kind == 'egf': c = [c[k]*factorial(k) for k in range(N)]
    return c

def theta_apply(P, A):
    p = Poly(P, n); res, T = 0, A
    for k in range(p.degree() + 1):
        res += p.coeff_monomial(n**k)*T; T = x*diff(T, x)
    return res

def E_raw(e, kind, Ps):
    r = len(Ps) - 1
    if kind == 'ogf':
        return sum(x**j*theta_apply(expand(P.subs(n, n + j)), e) for j, P in enumerate(Ps))
    return sum(theta_apply(expand(P.subs(n, n + r)), diff(e, x, r - j)) for j, P in enumerate(Ps))

def run(aid, NT=26):
    t = open(f'{SEQ}/{aid[:4]}/{aid}.seq').read()
    terms, off, conjs = batch.oeis(aid)
    terms = terms[:NT]
    lines = [l for l in t.splitlines() if re.match(rf'^%F {aid} (E\.g\.f\.|G\.f\.|O\.g\.f\.|g\.f\.)', l)]
    tried = []
    for line in lines:
        tr = translate(line, aid)
        if not tr: continue
        kind, e, s = tr
        try:
            c = coeffs(e, kind, len(terms) + off + 1)
        except Exception as ex:
            tried.append(s[:80]); continue
        # the g.f. may start at x^off or at x^0; accept either alignment
        al = None
        if all(c[off + i] == terms[i] for i in range(len(terms))): al = 'x^n'
        elif all(c[i] == terms[i] for i in range(len(terms))): al = 'shift'
        if al is None:
            tried.append(s[:80]); continue
        if al == 'shift' and off != 0:
            if kind != 'ogf': continue
            e = e*x**off
            c = coeffs(e, kind, len(terms) + off + 1)
            assert all(c[off + i] == terms[i] for i in range(len(terms)))
        out = {'id': aid, 'align': al, 'kind': kind, 'gf': s, 'offset': off, 'terms_checked': len(terms), 'results': []}
        for txt in conjs:
            try:
                Ps, rest = batch.parse_rec(txt)
            except Exception as ex:
                out['results'].append({'conj': txt[:160], 'skip': 'parse'}); continue
            if rest != 0:
                out['results'].append({'conj': txt[:160], 'skip': 'inhomogeneous'}); continue
            r = len(Ps) - 1
            a = {k: (c[k] if k < len(c) else None) for k in range(len(c))}
            # numeric instances on exact terms (index n refers to a(n) with a(k)=0 for k<0)
            num_bad = []
            for k in range(max(r, off), off + len(terms)):
                vals = [a.get(k - j) if k - j >= 0 else 0 for j in range(r + 1)]
                if any(v is None for v in vals): continue
                if sum(Ps[j].subs(n, k)*vals[j] for j in range(r + 1)) != 0: num_bad.append(k)
            Er = E_raw(e, kind, Ps)
            try:
                Es = simplify(radsimp(together(Er)))
            except Exception:
                Es = None
            res = {'conj': txt[:200], 'order': r, 'numeric_failures': num_bad}
            if Es is not None and Es.is_polynomial(x):
                P = Poly(Es, x) if Es != 0 else None
                if kind == 'ogf':
                    fails = [k for k in range(max(r, off), (P.degree() if P else -1) + 1) if P.coeff_monomial(x**k) != 0]
                else:
                    fails = [m + r for m in range(0, (P.degree() if P else -1) + 1)
                             if P.coeff_monomial(x**m) != 0 and m + r >= max(r, off)]
                # 60-digit random-point check
                mpmath.mp.dps = 60
                g = lambdify(x, Er - Es, 'mpmath')
                random.seed(hash(aid) & 0xffff)
                try:
                    worst = max(abs(g(mpmath.mpf(random.randint(1, 999))/100000)) for _ in range(5))
                    worst = float(worst)
                except Exception:
                    worst = None
                consistent = (fails == [k for k in num_bad if k <= (max(fails) if fails else -1)] and
                              all(k in fails for k in num_bad))
                res.update({'E': str(factor(Es)), 'exact_failures': fails, 'residual60': worst,
                            'numeric_agrees': consistent,
                            'verdict': ('TRUE n>=%d' % max(r, off)) if not fails else ('FALSE at %s, true after' % fails)})
            else:
                res.update({'E': None, 'verdict': 'UNDECIDED'})
            out['results'].append(res)
        return out
    return {'id': aid, 'skip': 'no usable g.f.', 'tried': tried[:3]}

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