#!/usr/bin/env python3
import lzma
import sys
from collections import Counter, defaultdict


def parse(path):
    clauses = []
    nvars = nclauses = 0
    with lzma.open(path, "rt", encoding="ascii") as f:
        cur = []
        for line in f:
            if line.startswith("c"):
                continue
            if line.startswith("p"):
                _, _, nvars, nclauses = line.split()
                nvars, nclauses = int(nvars), int(nclauses)
                continue
            for tok in line.split():
                lit = int(tok)
                if lit == 0:
                    clauses.append(cur)
                    cur = []
                else:
                    cur.append(lit)
    return nvars, nclauses, clauses


def main(path):
    nvars, nclauses, clauses = parse(path)
    long = [(i, c) for i, c in enumerate(clauses) if len(c) > 9]
    links = [c[-1] for _, c in long]
    linkset = {abs(x) for x in links}
    occ = defaultdict(list)
    for i, c in enumerate(clauses):
        for lit in c:
            v = abs(lit)
            if v in linkset:
                occ[v].append((i, lit, len(c), c))
    print(path, "vars", nvars, "clauses", nclauses, "long", len(long), "linkvars", len(linkset))
    print("long_index_first_last", long[0][0] if long else None, long[-1][0] if long else None)
    deg = Counter(len(occ[v]) for v in linkset)
    print("link_degree_hist", sorted(deg.items()))
    sig = Counter()
    for v in linkset:
        kinds = tuple(sorted((1 if lit > 0 else -1, ln) for _, lit, ln, _ in occ[v]))
        sig[kinds] += 1
    print("sig_top")
    for k, c in sig.most_common(10):
        print(c, k)
    for v in links[:8]:
        av = abs(v)
        print("link", v)
        for i, lit, ln, cl in occ[av]:
            print(" ", i, lit, ln, " ".join(map(str, cl[:20])))


if __name__ == "__main__":
    main(sys.argv[1])
