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


def clauses(path):
    opener = lzma.open if path.endswith(".xz") else open
    with opener(path, "rt", errors="replace") as f:
        for line in f:
            if not line or line[0] == "c":
                continue
            if line[0] == "p":
                parts = line.split()
                yield ("p", int(parts[2]), int(parts[3]))
                continue
            lits = [int(x) for x in line.split() if x != "0"]
            if lits:
                yield lits


def main(path):
    it = clauses(path)
    tag, nvars, nclauses = next(it)
    size = collections.Counter()
    signpat = collections.Counter()
    units = []
    first_non_negbin = None
    prefix_edges = []
    max_prefix_var = 0
    first = []
    for idx, c in enumerate(it, 1):
        if len(first) < 80:
            first.append(c)
        size[len(c)] += 1
        neg = sum(1 for x in c if x < 0)
        pos = len(c) - neg
        signpat[(len(c), neg, pos)] += 1
        if len(c) == 1:
            units.append(c[0])
        if first_non_negbin is None:
            if len(c) == 2 and c[0] < 0 and c[1] < 0:
                prefix_edges.append((-c[0], -c[1]))
                max_prefix_var = max(max_prefix_var, -c[0], -c[1])
            else:
                first_non_negbin = idx
    print(path)
    print("vars clauses", nvars, nclauses)
    print("size", sorted(size.items()))
    print("signpat top", signpat.most_common(20))
    print("prefix negbin clauses", len(prefix_edges), "maxvar", max_prefix_var, "first_non", first_non_negbin)
    print("units", len(units), "first", units[:80], "pos", sum(x > 0 for x in units), "neg", sum(x < 0 for x in units))
    print("first clauses after prefix:")
    for i, c in enumerate(first[max(0, (first_non_negbin or 1)-3):max(0, (first_non_negbin or 1)+25)], max(1, (first_non_negbin or 1)-2)):
        print(i, c)


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