"""Batch 3: run the batch2 pipeline with hand-transcribed generating functions.
Usage:
  python3 batch3.py check <A-id> <ogf|egf> "<sympy expr in x>"   -> does it reproduce OEIS terms?
  python3 batch3.py run <transcriptions.json> [ids...]          -> exact decision (JSON lines)
The expression may use: x, sqrt, exp, log, besseli(k, z), besselj, asin, acos, atan, sinh, cosh,
tanh, sin, cos, Rational, catalan_gf(z), motzkin_gf(z), pi, E.  It must equal sum a(n) x^n (ogf)
or sum a(n) x^n/n! (egf) with the OEIS offset (a(n)=0 below the offset)."""
import sys, json, re
sys.path.insert(0, '/home/user/oeisproofs')
import batch2 as b
import batch
from sympy import (symbols, sqrt, exp, log, besseli, besselj, asin, acos, atan, sinh, cosh, tanh,
                   sin, cos, Rational, pi, E, sympify)
x = symbols('x')
LOC = dict(x=x, sqrt=sqrt, exp=exp, log=log, besseli=besseli, besselj=besselj, asin=asin, acos=acos,
           atan=atan, sinh=sinh, cosh=cosh, tanh=tanh, sin=sin, cos=cos, Rational=Rational, pi=pi, E=E,
           catalan_gf=b.catalan_gf, motzkin_gf=b.motzkin_gf)

def parse(s):
    return eval(s, {'__builtins__': {}}, LOC)

def check(aid, kind, s, NT=26):
    terms, off, conjs = batch.oeis(aid)
    terms = terms[:NT]
    e = parse(s)
    c = b.coeffs(e, kind, len(terms) + off + 1)
    ok = all(c[off + i] == terms[i] for i in range(len(terms)))
    return ok, [str(v) for v in c[off:off + 8]], terms[:8]

def run_one(aid, kind, s):
    # monkeypatch translate so that b.run uses this expression
    orig = b.translate
    def tr(line, a):
        return (kind, parse(s), s)
    b.translate = tr
    try:
        t = open(f'{b.SEQ}/{aid[:4]}/{aid}.seq').read()
        if not re.search(rf'^%F {aid} (E\.g\.f\.|G\.f\.|O\.g\.f\.|g\.f\.)', t, re.M):
            # batch2.run only iterates over g.f. lines; inject a dummy line
            pass
        return b.run(aid)
    finally:
        b.translate = orig

if __name__ == '__main__':
    if sys.argv[1] == 'check':
        ok, got, want = check(sys.argv[2], sys.argv[3], sys.argv[4])
        print('MATCH' if ok else 'MISMATCH', 'computed', got, 'oeis', want)
    else:
        T = json.load(open(sys.argv[2]))
        ids = sys.argv[3:] or list(T)
        for aid in ids:
            v = T[aid]
            try:
                r = run_one(aid, v['kind'], v['expr'])
            except Exception as ex:
                r = {'id': aid, 'error': repr(ex)[:200]}
            print(json.dumps(r, default=str), flush=True)
