#!/usr/bin/env python3
import collections
import math
import sys
import lzma
from pathlib import Path


def open_dimacs(path):
    if str(path).endswith(".xz"):
        return lzma.open(path, "rt")
    return open(path, "rt")


def parse(path):
    nvars = nclauses = None
    clauses = []
    with open_dimacs(path) as f:
        cur = []
        for line in f:
            if not line or line[0] == "c":
                continue
            parts = line.split()
            if not parts:
                continue
            if parts[0] == "p":
                nvars = int(parts[2])
                nclauses = int(parts[3])
                continue
            for tok in parts:
                lit = int(tok)
                if lit == 0:
                    if cur:
                        clauses.append(cur)
                    cur = []
                else:
                    cur.append(lit)
    return nvars, nclauses, clauses


def main():
    for arg in sys.argv[1:]:
        p = Path(arg)
        nvars, nclauses, clauses = parse(p)
        lens = collections.Counter(map(len, clauses))
        pos = neg = 0
        deg = [0] * (nvars + 1)
        pdeg = [0] * (nvars + 1)
        ndeg = [0] * (nvars + 1)
        for cl in clauses:
            for lit in cl:
                v = abs(lit)
                deg[v] += 1
                if lit > 0:
                    pos += 1
                    pdeg[v] += 1
                else:
                    neg += 1
                    ndeg[v] += 1
        roots = []
        for k in range(1, int(math.sqrt(nvars)) + 2):
            if k * k * k == nvars:
                roots.append(f"{k}^3")
            if k * k * k + k * k * (k - 1) // 2 == nvars:
                roots.append(f"{k}^3+cell-aux?")
        print(p.name)
        print("  vars", nvars, "clauses", nclauses, "lens", dict(sorted(lens.items())))
        print("  polarity pos", pos, "neg", neg, "hints", ",".join(roots) or "-")
        print("  vars used", sum(1 for d in deg if d), "deg min/max", min(d for d in deg[1:] if d), max(deg))
        print("  units", [cl[0] for cl in clauses if len(cl) == 1][:20])
        print("  first long clauses:")
        for cl in [c for c in clauses if len(c) >= 10][:8]:
            print("   ", cl[:5], "...", cl[-5:], "len", len(cl))


if __name__ == "__main__":
    main()
