import struct
import zlib

def image(seq,value):
    body=struct.pack("<II",seq,value)
    return body+struct.pack("<I",zlib.crc32(body))+b"\x00"

def program(slot,at,value):
    if slot[at]&value != value:raise ValueError("不允许0写回1")
    slot[at]=value

def recover(slots):
    valid=[]
    for raw in slots:
        if len(raw)!=13 or raw[-1]!=0:continue
        if zlib.crc32(raw[:8])!=struct.unpack("<I",raw[8:12])[0]:continue
        valid.append(struct.unpack("<II",raw[:8]))
    return max(valid)[1] if valid else None

if __name__=="__main__":
    old=image(1,42);new=image(2,99)
    for stop in range(14):
        slot=bytearray(b"\xff"*13)
        for at,value in enumerate(new[:stop]):program(slot,at,value)
        result=recover([old,slot])
        assert result==(99 if stop==13 else 42)
    broken=bytearray(new);broken[4]^=1
    assert recover([old,broken])==42
    try:program(bytearray(b"\x00"),0,255);raise AssertionError()
    except ValueError:pass
    print("14个中断点只恢复42或99；半写从不作为新记录；新槽校验损坏后恢复42")
