"""Exact misère-play calculation for Kai Liang, arXiv:2611.29198, Conjectures 4.1 and 4.4.
Heaps are labeled to make option generation transparent; zero heaps have no moves.
N is True (the player to move wins). Under misère rules the terminal position is N.
"""
from functools import lru_cache
from itertools import product


def options(code, position):
    for i, heap in enumerate(position):
        for k, digit in enumerate(code, 1):
            if (heap == k and digit % 2 == 1) or (k < heap and digit >= 2):
                yield position[:i]+(heap-k,)+position[i+1:]


@lru_cache(None)
def wins(code, position):
    moves = list(options(code, position))
    return not moves or any(not wins(code, q) for q in moves)


def grid(code, top):
    # A separate bottom-up, labeled four-axis table. Each legal move lowers the sum.
    table = {}
    for pos in product(*(range(h+1) for h in top)):
        successors=[]
        for i,h in enumerate(pos):
            for new in range(h):
                k=h-new
                if k>len(code):continue
                mask=1 if new==0 else 2
                if code[k-1]&mask:
                    q=list(pos);q[i]=new;successors.append(table[tuple(q)])
        table[pos]=not successors or False in successors
    return table


SLICE = ((3,1,2,2), (2,2,7,2), (2,2,14,2))
FOLD = [((3,1,0,2), 5, (2,1,1,1)), ((3,1,2,2), 7, (1,1,2,2)),
        ((3,1,2,3), 7, (1,1,2,2)), ((3,3,1,2), 3, (2,1,1,1))]


def check(code,p,q):
    t=grid(code,tuple(map(max,zip(p,q))))
    assert all(wins(code,s)==v for s,v in t.items())
    assert t[p]!=t[q]
    return ('N' if t[p] else 'P','N' if t[q] else 'P',len(t))


if __name__=='__main__':
    code,p,q=SLICE
    key=lambda pos:(pos[2]%7,pos[3]%7,abs(pos[2]-pos[3])<=4)
    assert key(p)==key(q)
    print('4.1',key(p),p,q,check(code,p,q))
    print('Winning moves at the first position:', [a for a in options(code,p) if not wins(code,a)])
    for c,step,left in FOLD:
        right=(left[0]+step,)+left[1:]
        print('4.4',c,step,left,right,check(c,left,right))
