"""2kwas: full check of iis:2611.00306 (Hardin tables, round T3) with our own engine.

For every one of the 280 tables:
  1. reading check: T(n,k) from our engine equals every "Table starts" grid entry and every entry of the
     antidiagonal data (%S/%T/%U) with min(n,k) <= 5;
  2. engine check: the engine equals a literal enumeration of all finished n X k arrays for n*k <= 16;
  3. every explicit "Empirical for column k / row n" recurrence with k, n <= 4 is decided:
     with L = number of live states of our (unlumped) automaton, the defect
     e(n) = a(n) - sum c_i a(n-i) is u^T M^(n-1-r) g for n >= r+1, so it satisfies a linear recurrence of order <= L;
     if it vanishes on L consecutive values from n0 = max(N+1, r+1) it vanishes for all n >= n0.
usage: OEIS_SEQ_DIR=<dir with the 280 .seq files> python3 -I hardin_check.py claims.json OUT.json [ids...]
"""
import os, sys, json, time, re
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from multiprocessing import Pool
from hardin_engine import spec_for, engine, brute, T


def antidiagonal_entries(seqfile):
    lines = open(seqfile, encoding="utf-8").read().splitlines()
    data = "".join(l[11:].strip() for l in lines if l[:2] in ("%S", "%T", "%U"))
    vals = [int(x) for x in data.split(",") if x != ""]
    out = {}
    d, i = 1, 0
    while i < len(vals):
        for n in range(1, d + 1):          # antidiagonal d: T(1,d), T(2,d-1), ..., T(d,1)
            if i >= len(vals): break
            out[(n, d + 1 - n)] = vals[i]; i += 1
        d += 1
    return out


def extra_claims(seqfile):
    """explicit recurrences written as a(k)=... (A208637 rows); not counted in the paper's 664"""
    out = []
    mode = None
    for l in open(seqfile, encoding="utf-8").read().splitlines():
        if not l.startswith("%F"): continue
        t = l[11:].strip()
        if t.startswith("Empirical for column"): mode = "col"; continue
        if t.startswith("Empirical for row"): mode = "row"; continue
        m = re.fullmatch(r"(k|n)=(\d+): a\(k\)=(.*?)(?: for k>(\d+))?", t)
        if m and mode and int(m.group(2)) <= 4:
            rhs = m.group(3)
            coef = {}
            for sgn, c, dd in re.findall(r"([+-]?)(?:(\d+)\*)?a\(k-(\d+)\)", rhs):
                v = int(c) if c else 1
                coef[int(dd)] = coef.get(int(dd), 0) + (-v if sgn == "-" else v)
            assert not re.sub(r"([+-]?)(?:(\d+)\*)?a\(k-(\d+)\)", "", rhs).strip(), t
            r = max(coef)
            out.append({"mode": mode, "idx": int(m.group(2)), "coef": [coef.get(i, 0) for i in range(1, r + 1)],
                        "N": int(m.group(4)) if m.group(4) else None, "text": t, "extra": True})
    return out


def decide(spec, cl):
    w, mode = cl["idx"], cl["mode"]
    eng = engine(spec, w, mode)
    L = eng.live_states()
    c = cl["coef"]; r = len(c); N = cl["N"]
    n0 = max((N + 1) if N is not None else 1, r + 1)
    nmax = n0 + L - 1
    a = [None] + eng.sequence(nmax)            # a[1..nmax]
    def defect(n):
        return a[n] - sum(c[i - 1] * a[n - i] for i in range(1, r + 1))
    ok = all(defect(n) == 0 for n in range(n0, nmax + 1))
    # least n1 >= r+1 from which the recurrence holds (given ok)
    n1 = n0
    while ok and n1 - 1 >= r + 1 and defect(n1 - 1) == 0:
        n1 -= 1
    sharp = None
    if N is not None and N >= r + 1:
        sharp = defect(N) != 0
    return {"live_states": L, "order": r, "n0": n0, "checked_to": nmax, "holds": ok, "holds_from": n1 if ok else None,
            "sharp": sharp, "first_terms": a[1:9]}


def check_table(args):
    entry, seqdir = args
    aid = entry["id"]
    t0 = time.time()
    res = {"id": aid}
    try:
        spec = spec_for(aid, entry["name"])
    except Exception as ex:
        res["error"] = "no reading: %s" % ex
        return res
    res["family"] = spec["family"]
    # 1. reading check against the grid and the antidiagonal data
    want = {}
    for n, row in enumerate(entry["grid"], 1):
        for k, v in enumerate(row, 1):
            want.setdefault((n, k), set()).add(v)
    for key, v in antidiagonal_entries(os.path.join(seqdir, aid + ".seq")).items():
        want.setdefault(key, set()).add(v)
    inconsistent_source = [k for k, s in want.items() if len(s) > 1]
    cache = {}
    def Tc(n, k):
        if (n, k) not in cache:
            cache[(n, k)] = T(spec, n, k)
        return cache[(n, k)]
    nchk = 0; bad = []
    # compute whole columns/rows at once for speed
    for w in range(1, 6):
        ks = [k for (n, k) in want if k == w and n >= w]
        if ks:
            nmax = max(n for (n, k) in want if k == w and n >= w)
            seq = engine(spec, w, "col").sequence(nmax)
            for n in range(w, nmax + 1): cache[(n, w)] = seq[n - 1]
        ns = [n for (n, k) in want if n == w and k > w]
        if ns:
            kmax = max(k for (n, k) in want if n == w and k > w)
            seq = engine(spec, w, "row").sequence(kmax)
            for k in range(w + 1, kmax + 1): cache[(w, k)] = seq[k - 1]
    for (n, k), s in sorted(want.items()):
        if min(n, k) > 5: continue
        nchk += 1
        v = Tc(n, k)
        if v not in s:
            bad.append([n, k, v, sorted(s)])
    res["reading"] = {"entries_checked": nchk, "mismatches": bad[:10], "n_mismatch": len(bad),
                      "source_inconsistent": inconsistent_source[:5]}
    # 2. engine vs literal enumeration
    bb = []; nb = 0
    for n in range(1, 17):
        for k in range(1, 17):
            if n * k > 16: continue
            if spec["kind"] == "repeat" and n * k > 14: continue
            nb += 1
            x, y = brute(spec, n, k), Tc(n, k)
            if x != y: bb.append([n, k, x, y])
    res["enumeration"] = {"sizes_checked": nb, "mismatches": bb}
    # 3. claims
    claims = entry["claims"] + extra_claims(os.path.join(seqdir, aid + ".seq"))
    out = []
    for cl in claims:
        d = decide(spec, cl)
        d.update({"mode": cl["mode"], "idx": cl["idx"], "text": cl["text"], "N": cl["N"], "extra": cl.get("extra", False)})
        out.append(d)
    res["claims"] = out
    res["seconds"] = round(time.time() - t0, 1)
    return res


if __name__ == "__main__":
    claims_path, out_path = sys.argv[1], sys.argv[2]
    seqdir = os.environ.get("OEIS_SEQ_DIR", "/home/user/ext/hardin_oeis")
    entries = json.load(open(claims_path))
    if len(sys.argv) > 3:
        entries = [e for e in entries if e["id"] in set(sys.argv[3:])]
    # biggest first for load balance
    entries.sort(key=lambda e: -max([c["idx"] for c in e["claims"]] + [0]))
    with Pool(4) as p:
        results = []
        for r in p.imap_unordered(check_table, [(e, seqdir) for e in entries]):
            results.append(r)
            print(r["id"], r.get("family"), r.get("seconds"), "reading mism", r.get("reading", {}).get("n_mismatch"),
                  "enum mism", len(r.get("enumeration", {}).get("mismatches", [])),
                  "claims", sum(1 for c in r.get("claims", []) if c["holds"]), "/", len(r.get("claims", [])), flush=True)
    results.sort(key=lambda r: r["id"])
    json.dump(results, open(out_path, "w"), indent=0)
