"""Exact finite checks for the packing and lexicographic constructions.
Run with Python 3. No packages or external data are required.
"""
from fractions import Fraction
from itertools import combinations, product
from math import comb, isqrt
from random import Random


def check_packing(seed):
    rng = Random(seed)
    caps = [Fraction(0)]
    demands = [Fraction(0)]
    starts = []
    for _ in range(4):
        start = len(caps)
        starts.append(start)
        length = rng.randrange(380, 491)
        value = Fraction(1, rng.randrange(5, 13) * 2**start)
        caps.extend([value] * length)
        demands.extend(Fraction(1, 2**i) for i in range(start, start + length))
    ends = {}
    covered = set()
    for j in range(1, len(caps)):
        if caps[j] >= 4 * demands[j]:
            continue
        mass = Fraction(0)
        for m in range(j, len(caps)):
            mass += caps[m]
            if mass >= 16 * demands[j]:
                assert mass < 20 * demands[j]
                ends[j] = m
                covered.update(range(j, m + 1))
                break
        else:
            raise AssertionError('The supplied test profile ends inside a deficient block')
    tests = 0
    for start in starts:
        first_good = next(i for i in range(start, len(caps)) if i not in covered)
        assert first_good > start + 30
        cutoff = first_good
        n = 3 + isqrt(4 * caps[cutoff].denominator // caps[cutoff].numerator)
        e = comb(n, 2)
        used = set()
        for j in range(cutoff, 0, -1):
            if j not in ends:
                labels = [2*j-1]
            else:
                assert ends[j] < cutoff
                mass = Fraction(0)
                labels = []
                for i in range(j, ends[j] + 1):
                    if 2*i in used:
                        continue
                    labels.append(2*i)
                    mass += caps[i]
                    if mass >= 2 * demands[j]:
                        break
                assert 2 * demands[j] <= mass < 6 * demands[j]
            assert used.isdisjoint(labels)
            used.update(labels)
            # In these tests the two caps of pair i are equal.
            assert sum(int(e * caps[(label+1)//2]) for label in labels) >= int(e * demands[j])
        tests += 1
    return tests


def cycle_color(x, y):
    return 0 if (x-y) % 5 in (1, 4) else 1


def lex_color(x, y, palettes):
    for a, b, offset in zip(x, y, palettes):
        if a != b:
            return offset + cycle_color(a, b)
    raise ValueError('An edge has distinct endpoints')


def check_products():
    vertices = list(product(range(5), repeat=2))
    for shared, forbidden in [(False, 3), (True, 5)]:
        palettes = [0, 0 if shared else 2]
        colors = {(x, y): lex_color(x, y, palettes) for x, y in combinations(vertices, 2)}
        for clique in combinations(vertices, forbidden):
            assert len({colors[edge] for edge in combinations(clique, 2)}) > 1
        if not shared:
            assert 5 * sum(c >= 2 for c in colors.values()) <= len(colors)


if __name__ == '__main__':
    print('Verified', sum(check_packing(s) for s in range(8)),
          'finite cutoffs with disjoint integer capacities')
    check_products()
    print('Verified all triples and all five-sets in the 25-vertex product tests')
