"""Exhaustive certificate for Kai Liang, Open Problem 6.2 of arXiv:2611.29198.
The finite checks and the translation argument in the accompanying proof together
cover every heap size. All Boolean values below label P (previous player wins).
"""
from functools import lru_cache
from itertools import product

CODE=(3,1,2,3)
FIXED=((0,0),(0,1),(0,2),(1,1),(1,2))
SMALL,GAP,PERIOD,STEP=19,6,7,4
P_ROWS=({1},{5},{0,1},{3,4},set(),{2,3,6},set())


def options(a,b,s,d):
    pos=(a,b,s,s+d)
    for i,h in enumerate(pos):
        for k,c in enumerate(CODE,1):
            if (h==k and c&1) or (h>k and c&2):
                q=list(pos);q[i]-=k
                x,y=sorted(q[2:]); yield (*sorted(q[:2]),x,y-x)


@lru_cache(None)
def direct(a,b,s,d):
    child=list(options(a,b,s,d))
    return bool(child) and not any(direct(*q) for q in child)


def reduce_coord(v,threshold):
    return v if v<threshold else threshold+(v-threshold)%PERIOD


# Only values in this finite dictionary define the global candidate.
base={(a,b,s,d):direct(a,b,s,d) for a,b in FIXED
      for s,d in product(range(SMALL+PERIOD),range(GAP+PERIOD))}

def candidate(a,b,s,d):
    return base[a,b,reduce_coord(s,SMALL),reduce_coord(d,GAP)]


def closing_recurrence():
    count=0
    for a,b in FIXED:
        for s,d in product(range(SMALL+PERIOD+STEP), range(GAP+PERIOD+STEP)):
            child=list(options(a,b,s,d))
            label=bool(child) and not any(candidate(*q) for q in child)
            assert candidate(a,b,s,d)==label,(a,b,s,d)
            count+=1
    return count


def bulk_loses(x,y):
    s,d=min(x,y),abs(x-y)
    assert s>=13
    return d>0 and s%7 in P_ROWS[d%7]


if __name__=='__main__':
    print('Finite recurrence equations checked:',closing_recurrence())
    for s,d in product(range(13,SMALL+PERIOD),range(GAP+PERIOD)):
        assert candidate(1,2,s,d)==bulk_loses(s,s+d)
    assert candidate(1,2,12,0) and not candidate(1,2,13,0)
    for d,r in enumerate(P_ROWS):print('gap mod 7:',d,'losing residues for a positive gap:',sorted(r))
    print('Bulk condition verified on every representative.')
