"""Check AutoGraphForge 0caab573. Optionally scan McKay's eul3c to eul10c files."""

import argparse
from fractions import Fraction
from itertools import combinations
from pathlib import Path


WITNESS = "I?aJAaKnG"


def decode_graph6(record):
    """Decode the one-byte order and column-major upper triangle of a small graph."""
    n = ord(record[0]) - 63
    num_bits = n * (n - 1) // 2
    if not 0 <= n < 63 or len(record) != 1 + (num_bits + 5) // 6:
        raise ValueError(f"Invalid short graph6 record {record!r}")
    if any(not 63 <= ord(char) <= 126 for char in record):
        raise ValueError(f"Invalid graph6 character in {record!r}")
    bits = "".join(f"{ord(char) - 63:06b}" for char in record[1:])
    neighbors = [set() for _ in range(n)]
    index = 0
    for v in range(n):
        for u in range(v):
            if bits[index] == "1":
                neighbors[u].add(v)
                neighbors[v].add(u)
            index += 1
    return neighbors


def connected_even_graph(neighbors):
    if not neighbors or any(len(row) % 2 for row in neighbors):
        return False
    seen = {0}
    stack = [0]
    while stack:
        for v in neighbors[stack.pop()] - seen:
            seen.add(v)
            stack.append(v)
    return len(seen) == len(neighbors)


def colorable(neighbors, limit):
    order = sorted(range(len(neighbors)), key=lambda v: -len(neighbors[v]))
    colors = [-1] * len(order)

    def visit(index):
        if index == len(order):
            return True
        v = order[index]
        forbidden = {colors[u] for u in neighbors[v]}
        for color in range(limit):
            if color in forbidden:
                continue
            colors[v] = color
            if visit(index + 1):
                return True
        colors[v] = -1
        return False

    return visit(0)


def check_witness():
    neighbors = decode_graph6(WITNESS)
    edges = {(u, v) for u, row in enumerate(neighbors) for v in row if u < v}
    clique = set(combinations([0, 4, 5, 8, 9], 2))
    cycle = {(2, 9), (2, 6), (1, 6), (1, 7), (3, 7), (3, 9)}
    assert edges == clique | cycle
    assert connected_even_graph(neighbors)
    n, m = len(neighbors), len(edges)
    chi = next(k for k in range(1, n + 1) if colorable(neighbors, k))
    average = Fraction(2 * m, n)
    bound = Fraction(3 * m, n)
    assert (n, m, chi) == (10, 16, 5) and chi > bound
    print(f"{WITNESS}   n={n} m={m} Eulerian=True chi={chi} average={average} bound={bound}")


def check_census(directory):
    counts = {3: 1, 4: 1, 5: 4, 6: 8, 7: 37, 8: 184, 9: 1782, 10: 31026}
    for n, expected in counts.items():
        rows = (directory / f"eul{n}c.g6").read_text(encoding="ascii").splitlines()
        assert len(rows) == len(set(rows)) == expected
        failures = []
        for i, record in enumerate(rows, 1):
            neighbors = decode_graph6(record)
            assert len(neighbors) == n and connected_even_graph(neighbors)
            m = sum(len(row) for row in neighbors) // 2
            if not colorable(neighbors, 3 * m // n):
                failures.append((i, record))
        print(f"n={n} graphs={len(rows)} counterexamples={failures}")
        assert failures == ([(13472, WITNESS)] if n == 10 else [])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("census_directory", nargs="?", type=Path)
    args = parser.parse_args()
    check_witness()
    if args.census_directory is not None:
        check_census(args.census_directory)
