#!/usr/bin/env python3
import lzma
import os
import sys


def read_clauses(path, limit=None):
    opener = lzma.open if path.endswith(".xz") else open
    with opener(path, "rt", encoding="ascii", errors="replace") as f:
        for line in f:
            if line.startswith("c") or line.startswith("p"):
                continue
            vals = [int(x) for x in line.split()]
            if vals and vals[-1] == 0:
                vals.pop()
            if vals:
                yield vals


def main():
    for path in sys.argv[1:]:
        it = iter(read_clauses(path))
        triples = []
        while True:
            try:
                c1, c2, c3 = next(it), next(it), next(it)
            except StopIteration:
                break
            if (
                len(c1) == len(c2) == len(c3) == 2
                and c1[0] < 0 and c1[1] < 0
                and c2[0] < 0 and c2[1] < 0
                and c3[0] > 0 and c3[1] < 0
                and -c2[0] == c3[0]
                and c1[0] == c2[1]
                and c1[1] == c3[1]
            ):
                x = c3[0]
                a = -c1[0]
                b = -c1[1]
                triples.append((x, a, b))
            else:
                break
        print(os.path.basename(path), "ntriples", len(triples))
        if triples:
            print(" first", triples[:5])
            print(" last", triples[-5:])
            # summarize b gaps
            gaps = []
            prev_b = triples[0][2]
            run = 1
            runs = []
            for _, _, b in triples[1:]:
                if b == prev_b + 1:
                    run += 1
                else:
                    gaps.append((prev_b, b, b - prev_b))
                    runs.append(run)
                    run = 1
                prev_b = b
            runs.append(run)
            print(" b_runs_first20", runs[:20], "num_runs", len(runs), "gaps_first10", gaps[:10])


if __name__ == "__main__":
    main()
