"""Parse 'Empirical for column k / row n' claims (k, n <= 4) from OEIS internal-format .seq files."""
import re, sys, os, json

def parse_seq(path):
    lines = open(path, encoding="utf-8").read().splitlines()
    aid = os.path.basename(path)[:7]
    name = " ".join(l[11:] for l in lines if l.startswith("%N"))
    grid = []
    in_grid = False
    for l in lines:
        if l[:2] in ("%C", "%e") and "Table starts" in l:      # A279709 has its grid in %e lines
            in_grid = True; tag = l[:2]; continue
        if in_grid:
            if l[:2] == tag and re.fullmatch(r"\s*\.[0-9.]+\s*", l[11:]):
                grid.append([int(x) for x in l[11:].strip().strip(".").split(".") if x != ""])
            else:
                in_grid = False
    claims, other = [], []
    mode = None
    for l in lines:
        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.match(r"(k|n)=(\d+):\s*(.*)$", t)
        if not m or mode is None:
            if mode is not None: other.append(t)
            continue
        idx = int(m.group(2)); rest = m.group(3)
        if idx > 4:
            continue
        if rest.startswith("["):
            other.append((mode, idx, rest)); continue
        mm = re.fullmatch(r"a\(n\) = (.*?)(?: for n>(\d+))?", rest)
        if not mm:
            other.append((mode, idx, rest)); continue
        rhs, N = mm.group(1), (int(mm.group(2)) if mm.group(2) else None)
        terms = re.findall(r"([+-]?)\s*(?:(\d+)\*)?a\(n-(\d+)\)", rhs)
        rebuilt = " ".join(rhs.split())
        coef = {}
        for sgn, c, d in terms:
            v = int(c) if c else 1
            if sgn == "-": v = -v
            coef[int(d)] = coef.get(int(d), 0) + v
        # make sure the whole rhs was consumed by the term regex (only linear homogeneous recurrences)
        check = re.sub(r"([+-]?)\s*(?:(\d+)\*)?a\(n-(\d+)\)", "", rhs).strip()
        if check:
            other.append((mode, idx, rest)); continue
        r = max(coef)
        claims.append({"mode": mode, "idx": idx, "coef": [coef.get(i, 0) for i in range(1, r + 1)],
                       "N": N, "text": rest})
    return {"id": aid, "name": name, "grid": grid, "claims": claims, "other": other}

if __name__ == "__main__":
    d = sys.argv[1]
    out = []
    for f in sorted(os.listdir(d)):
        if f.endswith(".seq"):
            out.append(parse_seq(os.path.join(d, f)))
    json.dump(out, open(sys.argv[2], "w"), indent=0)
    nc = sum(1 for e in out for c in e["claims"] if c["mode"] == "col")
    nr = sum(1 for e in out for c in e["claims"] if c["mode"] == "row")
    print("tables", len(out), "column claims", nc, "row claims", nr, "total", nc + nr)
    oth = [(e["id"], o) for e in out for o in e["other"]]
    print("unparsed/other lines (k,n<=4):", len([o for o in oth if isinstance(o[1], tuple)]))
    for o in oth:
        if isinstance(o[1], tuple) and not o[1][2].startswith("["): print("  ", o)
    print("grids missing:", [e["id"] for e in out if not e["grid"]])
