#!/usr/bin/env python3
"""Small DIMACS profiler for the SCPC family.

Usage:
    xz -dc /data/train/example.cnf.xz | ./tools/profile.py
    ./tools/profile.py formula.cnf
"""

from __future__ import annotations

import collections
import sys


def lines() -> list[str]:
    if len(sys.argv) == 2:
        with open(sys.argv[1], "r", encoding="ascii") as handle:
            return handle.readlines()
    return sys.stdin.readlines()


def main() -> int:
    nvars = nclauses = 0
    hist: collections.Counter[int] = collections.Counter()
    positive = negative = mixed = 0
    pos_lits = neg_lits = 0

    for line in lines():
        if not line or line[0] in "c%\n":
            continue
        if line.startswith("p "):
            fields = line.split()
            nvars = int(fields[2])
            nclauses = int(fields[3])
            continue
        lits = [int(x) for x in line.split() if x != "0"]
        if not lits:
            continue
        hist[len(lits)] += 1
        p = sum(1 for lit in lits if lit > 0)
        q = len(lits) - p
        pos_lits += p
        neg_lits += q
        if p == len(lits):
            positive += 1
        elif q == len(lits):
            negative += 1
        else:
            mixed += 1

    print(f"vars={nvars} clauses={nclauses}")
    print(f"positive_clauses={positive} negative_clauses={negative} mixed_clauses={mixed}")
    print(f"positive_literals={pos_lits} negative_literals={neg_lits}")
    print("length_hist=" + ",".join(f"{k}:{hist[k]}" for k in sorted(hist)))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
