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


def open_dimacs(path):
    if path.endswith(".xz"):
        return lzma.open(path, "rt", encoding="ascii", errors="ignore")
    return open(path, "rt", encoding="ascii", errors="ignore")


def main(path):
    nvars = nclauses = None
    size_hist = collections.Counter()
    pos = collections.Counter()
    neg = collections.Counter()
    first = []
    short = collections.Counter()
    units = []
    clauses_seen = 0

    with open_dimacs(path) as f:
        clause = []
        for line in f:
            if not line or line[0] == "c":
                continue
            if line[0] == "p":
                parts = line.split()
                nvars = int(parts[2])
                nclauses = int(parts[3])
                continue
            for tok in line.split():
                lit = int(tok)
                if lit == 0:
                    clauses_seen += 1
                    k = len(clause)
                    size_hist[k] += 1
                    if len(first) < 12:
                        first.append(tuple(clause))
                    if k <= 4:
                        short[tuple(sorted(clause, key=lambda x: (abs(x), x)))] += 1
                    if k == 1:
                        units.append(clause[0])
                    for x in clause:
                        if x > 0:
                            pos[x] += 1
                        else:
                            neg[-x] += 1
                    clause = []
                else:
                    clause.append(lit)

    touched = set(pos) | set(neg)
    degs = [pos[v] + neg[v] for v in touched]
    pure_pos = sum(1 for v in touched if pos[v] and not neg[v])
    pure_neg = sum(1 for v in touched if neg[v] and not pos[v])
    both = sum(1 for v in touched if pos[v] and neg[v])

    print(path)
    print(f"p cnf {nvars} {nclauses}; parsed {clauses_seen}")
    print("sizes", " ".join(f"{k}:{v}" for k, v in sorted(size_hist.items())[:20]))
    print(f"vars touched {len(touched)} pure_pos {pure_pos} pure_neg {pure_neg} both {both}")
    if degs:
        degs.sort()
        for q in [0, 0.25, 0.5, 0.75, 0.9, 0.99, 1.0]:
            idx = min(len(degs) - 1, int(q * (len(degs) - 1)))
            print(f"deg q{q:g} {degs[idx]}")
        print(f"mean deg {sum(degs)/len(degs):.2f}")
    print("units", len(units), units[:30])
    print("first")
    for c in first:
        print(" ", " ".join(map(str, c)), "0")


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