"""Look for 18 axis-parallel cubes on at most 81 points of {0,1,2,3}^4."""
from itertools import product
import z3
from time import monotonic
from pathlib import Path


def grid(k):
    return list(product(range(k),repeat=4))


def search():
    solver=z3.SolverFor('QF_FD')
    solver.set(timeout=200000)
    cells = {p:z3.Bool('v'+''.join(map(str,p))) for p in grid(4)}
    cubes = {}
    for h in (1,2,3):
        cubes[h] = {}
        for a in grid(4-h):
            var = z3.Bool('c'+str(h)+''.join(map(str,a)))
            cubes[h][a] = var
            for bits in grid(2):
                p=tuple(x+h*y for x,y in zip(a,bits))
                solver.add(z3.Implies(var,cells[p]))
    solver.add(z3.PbLe([(v,1) for v in cells.values()],81))
    solver.add(z3.PbEq([(v,1) for row in cubes.values() for v in row.values()],18))
    # More than seventeen selected cubes force a length-two cube because at most
    # sixteen can be unit cubes and only one length-three cube fits the box.
    # Coordinate reflections send any selected side-two cube to this one.
    solver.add(cubes[2][(0,)*4])
    start=monotonic()
    status=solver.check()
    print('grid [4]^4:',status,'wall seconds',round(monotonic()-start,2),flush=True)
    if status==z3.sat:
        model=solver.model()
        points={p for p,v in cells.items() if z3.is_true(model.eval(v))}
        actual={h:[a for a in grid(4-h) if all(tuple(x+h*y for x,y in zip(a,b)) in points for b in grid(2))] for h in (1,2,3)}
        assert len(points)<=81 and sum(map(len,actual.values()))>=18
        Path('barcode-counterexample.txt').write_text(repr(sorted(points))+'\n'+repr(actual))
    elif status==z3.unknown:
        print(solver.reason_unknown(),flush=True)


if __name__=='__main__':
    search()
