"""Collects the logs of run_third.sh (IIS-Q-0003): the third-party solvers z3 and HiGHS.

usage: python3 -I work/capset/q0003/q3_third_collect.py LOGDIR
The script reads the files q3_third_SOLVER_LAYER_KIND.log in LOGDIR.  Each file holds the output
of q3_third.py for one solver, one layer and one kind of puncture.  An instance is one puncture
set and one budget.  Test 1 asks the solver to find a family of directions of the size of the
table.  Test 2 asks the solver to prove that a family with one direction more is not possible.
An instance "agrees" when the solver passes test 1 and test 2.  An instance is "no decision"
when a call reaches its time limit.  An instance "disagrees" when the solver proves the opposite
of the table in test 1 or in test 2.  The script stops with an error if there is a disagreement
or a log without exit 0.
Revision 2 (28 November 2026): revision 1 added the numbers of test 1 and test 2 with a wrong
key, so the two totals were 0.  The lines of each log were correct.
"""
import glob
import os
import re
import sys

RE_FINAL = re.compile(r"solver (\w+), layer (\d+): instances (\d+), agree (\d+), disagree (\d+), no decision (\d+), longest solve ([\d.]+) s, seconds (\d+)$")
RE_KIND = re.compile(r"(\w+) budget (\d+) : sets (\d+) : test 1 found (\d+), test 2 proved (\d+), agree (\d+), disagree (\d+), no decision (\d+) : longest solve ([\d.]+) s$")
RE_EXIT = re.compile(r"exit (\d+)$")

logdir = sys.argv[1]
tot = {}    # (solver, layer) : instances, agree, disagree, longest call
det = {}    # (solver, layer, kind) : sets, test 1 found, test 2 proved, agree, disagree, no decision
problems = []
nlogs = 0


def add(table, key, values):
    """Adds the numbers to the row of the key.  A float is a time: the row keeps the longest time."""
    row = table.get(key)
    if row is None:
        table[key] = list(values)
        return
    for i, v in enumerate(values):
        row[i] = max(row[i], v) if isinstance(v, float) else row[i] + v


for path in sorted(glob.glob(os.path.join(logdir, "q3_third_*_L*_*.log"))):
    nlogs += 1
    name = path.rsplit("/", 1)[-1]
    with open(path, encoding="utf-8") as f:
        lines = [ln.rstrip("\n") for ln in f]
    finals = [m for m in (RE_FINAL.fullmatch(ln) for ln in lines) if m]
    codes = [int(m.group(1)) for ln in lines for m in [RE_EXIT.search(ln)] if m]
    if len(finals) != 1 or codes != [0]:
        problems.append("%s has %d final lines and exit codes %s" % (name, len(finals), codes))
    if not finals:
        continue
    final = finals[0]
    solver, layer = final.group(1), int(final.group(2))
    add(tot, (solver, layer), [int(final.group(3)), int(final.group(4)), int(final.group(5)), float(final.group(7))])
    for m in (m for m in (RE_FINAL.fullmatch(ln) for ln in lines) if m):
        if m.group(1) != solver or int(m.group(2)) != layer:
            problems.append("%s holds a final line of another solver or layer" % name)
    for m in (m for m in (RE_KIND.fullmatch(ln) for ln in lines) if m):
        kind = m.group(1)
        if not name.endswith("_%s.log" % kind):
            problems.append("%s holds a line of kind %s" % (name, kind))
        sets, found, proved, agree, disagree, nodec = (int(m.group(i)) for i in range(3, 9))
        # an instance with test 1 found and test 2 unknown is in "found" and in "no decision"
        if sets != agree + disagree + nodec or not (agree <= found and agree <= proved and proved <= found):
            problems.append("%s: the sets of budget %s do not add up" % (name, m.group(2)))
        add(det, (solver, layer, kind), [sets, found, proved, agree, disagree, nodec])
for name in problems:
    print("PROBLEM: %s" % name)
print("solver : layer : instances : test 1 found : test 2 proved : agree : no decision : disagree : longest call (s)")
for key in sorted(tot):
    row = tot[key]
    found = sum(d[1] for k, d in det.items() if k[0] == key[0] and k[1] == key[1])
    proved = sum(d[2] for k, d in det.items() if k[0] == key[0] and k[1] == key[1])
    print("%s : %d : %d : %d : %d : %d : %d : %d : %.2f" % (
        key[0], key[1], row[0], found, proved, row[1], row[0] - row[1] - row[2], row[2], row[3]))
print("solver : layer : kind : instances : test 1 found : test 2 proved : agree : disagree : no decision")
for key in sorted(det):
    d = det[key]
    print("%s : %d : %s : %d : %d : %d : %d : %d : %d" % (key[0], key[1], key[2], d[0], d[1], d[2], d[3], d[4], d[5]))
for solver in sorted({k[0] for k in tot}):
    rows = [r for k, r in tot.items() if k[0] == solver]
    print("%s : both layers : instances %d, test 1 found %d, test 2 proved %d, agree %d, no decision %d, disagree %d" % (
        solver, sum(r[0] for r in rows), sum(d[1] for k, d in det.items() if k[0] == solver),
        sum(d[2] for k, d in det.items() if k[0] == solver), sum(r[1] for r in rows),
        sum(r[0] - r[1] - r[2] for r in rows), sum(r[2] for r in rows)))
print("logs %d, problems %d" % (nlogs, len(problems)))
if problems or not tot:
    sys.exit(1)
