#!/usr/bin/env python3
"""Small CNF profiler used during reverse engineering.

The solver does not depend on this script.  It summarizes DIMACS structure for
the training formulas and is kept as a notebook aid for future iterations.
"""

from __future__ import annotations

import collections
import glob
import lzma
import os


def profile(path: str) -> None:
    sizes: collections.Counter[int] = collections.Counter()
    pos = neg = clauses = max_var = units = 0
    with lzma.open(path, "rt") as f:
        for line in f:
            if not line.strip() or line[0] in "c%":
                continue
            if line.startswith("p "):
                parts = line.split()
                max_var = int(parts[2])
                continue
            lits = [int(x) for x in line.split() if x != "0"]
            if not lits:
                continue
            clauses += 1
            sizes[len(lits)] += 1
            units += len(lits) == 1
            for lit in lits:
                pos += lit > 0
                neg += lit < 0
    name = os.path.basename(path).split("-", 1)[-1].replace(".cnf.xz", "")
    print(
        f"{name:34s} vars={max_var:5d} clauses={clauses:6d} "
        f"units={units:4d} sizes={dict(sorted(sizes.items()))} "
        f"pos={pos:6d} neg={neg:6d}"
    )


def main() -> None:
    for path in sorted(glob.glob("/data/train/*.cnf.xz")):
        profile(path)


if __name__ == "__main__":
    main()
