# brute force checker for ties.c
# python check.py ./ties L [threads chunk_bytes seg_bytes]
# simple sieve, walk every prime, then compare with what ties prints
import subprocess
import sys

PAIRS = [(1, 9), (7, 9), (1, 7), (3, 7), (1, 3), (3, 9)]
TRIPLES = [(1, 3, 9), (1, 3, 7), (3, 7, 9), (1, 7, 9)]
COMBS = PAIRS + TRIPLES + [(1, 3, 7, 9)]


def name(g):
    return "[" + ",".join(map(str, g)) + "]"


def brute(L):
    s = bytearray([1]) * L
    s[0:2] = b"\0\0"
    for i in range(2, int(L ** 0.5) + 1):
        if s[i]:
            s[i * i::i] = bytes(len(range(i * i, L, i)))
    c = {1: 0, 3: 0, 7: 0, 9: 0}
    ties = {g: 0 for g in COMBS}
    last = {g: 0 for g in COMBS}
    first19, big = [], []
    for p in range(2, L):
        if not s[p] or p % 10 not in c:
            continue
        d = p % 10
        c[d] += 1
        for g in COMBS:
            if d in g and len({c[x] for x in g}) == 1:
                ties[g] += 1
                last[g] = p
                if g == (1, 9) and len(first19) < 40:
                    first19.append(p)
                if len(g) > 2:
                    big.append((COMBS.index(g), p))
    out = ["counts %d %d %d %d" % (c[1], c[3], c[7], c[9])]
    for g in COMBS:
        out.append("%s %s %d" % (name(g), last[g] if ties[g] else "none", ties[g]))
    out.append("first19 " + " ".join(map(str, first19)))
    for k, p in sorted(big):
        out.append("tie %s %d" % (name(COMBS[k]), p))
    return out


# pull the same lines out of ties' output
def from_c(binary, args):
    txt = subprocess.run([binary] + args, capture_output=True, text=True, check=True).stdout
    out = []
    for line in txt.splitlines():
        f = line.split()
        if line.startswith("counts of primes"):
            out.append("counts " + " ".join(f[8:12]))
        elif f and f[0].startswith("[") and len(f) == 3:
            out.append(" ".join(f))
        elif line.startswith("first [1,9] ties:"):
            out.append("first19 " + " ".join(f[3:]))
        elif line.startswith("tie "):
            out.append(line)
    return out


if __name__ == "__main__":
    binary, L = sys.argv[1], int(float(sys.argv[2]))
    a, b = brute(L), from_c(binary, [str(L)] + sys.argv[3:])
    if a == b:
        print("MATCH L=%d (%d lines)" % (L, len(a)))
    else:
        print("MISMATCH L=%d" % L)
        for x, y in zip(a, b):
            if x != y:
                print("  brute:", x, "\n  ties: ", y)
        sys.exit(1)
