#!/usr/bin/env python3
"""Module 12: private, deterministic storage experiments. Python 3.10+.
All files live in TemporaryDirectory. No external dependencies or network access.
Single writer only; no process locking, concurrent compaction, or power-loss proof.
"""
import bisect
import hashlib
import json
import os
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import zlib

MAGIC = b'F12\x01'
HEADER = struct.Struct('>IBHH')  # sequence, operation, key bytes, value bytes
MAX_KEY, MAX_VALUE = 64, 256
OPS = [('a','1'),('b','2'),('c','3'),('b','4'),('a',None),('d','5'),('e','6'),('c',None),('b','7')]

class Corruption(ValueError):
    pass

class TornTail(Corruption):
    pass

def show(value):
    return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':'))

def checked(key, value):
    if not isinstance(key, str) or not key or len(key.encode('utf-8')) > MAX_KEY:
        raise ValueError('invalid key')
    if value is not None and (not isinstance(value, str) or len(value.encode('utf-8')) > MAX_VALUE):
        raise ValueError('invalid value')
    return key.encode('utf-8'), b'' if value is None else value.encode('utf-8')

def encode(seq, key, value):
    k, v = checked(key, value)
    if type(seq) is not int or not 1 <= seq <= 0xffffffff:
        raise ValueError('invalid sequence')
    return HEADER.pack(seq, 0 if value is None else 1, len(k), len(v)) + k + v

def decode_one(data, offset):
    if len(data) - offset < HEADER.size:
        raise TornTail(f'incomplete header at {offset}')
    seq, op, nk, nv = HEADER.unpack_from(data, offset)
    if not seq or op not in (0,1) or not 1 <= nk <= MAX_KEY or nv > MAX_VALUE or (op == 0 and nv):
        raise Corruption(f'invalid header at {offset}')
    end = offset + HEADER.size + nk + nv
    if end > len(data):
        raise TornTail(f'incomplete payload at {offset}')
    try:
        key = data[offset+HEADER.size:offset+HEADER.size+nk].decode('utf-8')
        value = data[offset+HEADER.size+nk:end].decode('utf-8') if op else None
    except UnicodeDecodeError as error:
        raise Corruption(f'invalid UTF-8 at {offset}') from error
    return (seq, key, value), end

def parse(data):
    if data[:4] != MAGIC:
        raise Corruption('unsupported file header')
    records, offset = [], 4
    while offset < len(data):
        start = offset
        record, offset = decode_one(data, offset)
        records.append((*record, start, offset-start))
    return records

def blob(records):
    return MAGIC + b''.join(encode(*r[:3]) for r in records)

def records(ops=OPS):
    return [(i,k,v) for i,(k,v) in enumerate(ops,1)]

def resolved(rows):
    latest = {}
    for seq,key,value,*_ in rows:
        if key not in latest or seq > latest[key][0]:
            latest[key] = (seq,value)
    return {k:v for k,(_,v) in sorted(latest.items()) if v is not None}

def write_sync(path, data):
    with path.open('wb') as f:
        view = memoryview(data)
        while view:
            n = f.write(view)
            if not n:
                raise OSError('short write without progress')
            view = view[n:]
        f.flush()
        os.fsync(f.fileno())

def append_sync(path, row):
    data=encode(*row)
    with path.open('ab') as f:
        view=memoryview(data)
        while view:
            n=f.write(view)
            if not n: raise OSError('short append without progress')
            view=view[n:]
        f.flush()
        os.fsync(f.fileno())

def sync_dir(path):
    fd = os.open(path, os.O_RDONLY)
    try:
        os.fsync(fd)
    finally:
        os.close(fd)

def publish(path, data):
    temporary = path.with_name(path.name + '.tmp')
    write_sync(temporary, data)
    os.replace(temporary, path)
    sync_dir(path.parent)

def mode_api(root):
    state = {}
    for seq,key,value in records(OPS[:5]):
        checked(key,value)
        if value is None: state.pop(key,None)
        else: state[key] = value
        print(f'{seq}: {"delete" if value is None else "put"} {key} -> {show(state)}')
    print('get missing ->', show(state.get('z')))
    before = state.copy()
    try: checked('x'*65,'1')
    except ValueError: print('65-byte key rejected; state unchanged:', str(state == before).lower())

def mode_tradeoffs(root):
    rows = records()
    p = root/'append.bin'; write_sync(p,blob(rows))
    scan = parse(p.read_bytes())
    # Sorted immutable runs are produced by the exact three-distinct-key policy.
    _, runs, _ = lsm_states()
    for i,run in enumerate(runs): write_sync(root/f'run{i}.bin',blob(run))
    # Reopen the files to verify their contents. Probe counts below are logical
    # comparisons after decoding, not file reads or device I/O.
    stored_runs = [parse((root/f'run{i}.bin').read_bytes()) for i in range(len(runs))]
    # Binary search over current keys models ordered narrowing, not a B-tree.
    current = resolved(rows)
    keys = sorted(current)
    def tree_probe(key):
        lo,hi,count = 0,len(keys),0
        while lo < hi:
            mid=(lo+hi)//2; count+=1
            if keys[mid] == key: return current[key], count
            if key < keys[mid]: hi=mid
            else: lo=mid+1
        return None, count
    def run_probe(key):
        count=0
        for run in stored_runs:
            for row in run:
                count+=1
                if row[1] == key: return row[2], count
        return None, count
    reopened = resolved(scan)
    for key in (*sorted({row[1] for row in rows}), 'z'):
        answers = (reopened.get(key), run_probe(key)[0], tree_probe(key)[0])
        if not answers[0] == answers[1] == answers[2]:
            raise AssertionError(f'lookup paths disagree for {key}: {answers}')
    answer, newest_count = run_probe('b')
    print('operations:', len(rows))
    print('append file bytes:', p.stat().st_size, '; records examined for b:', len(scan))
    print('sorted run bytes:', sum((root/f'run{i}.bin').stat().st_size for i in range(len(runs))), '; records examined for b:', newest_count)
    print('balanced current-key search comparisons for b:', tree_probe('b')[1])
    print('all answers for b:', show(answer))
    print('tree comparison excludes file writes, recovery and page I/O')

def mode_snapshot(root):
    path = root/'dictionary.json'
    first={'apple':'fruit','banana':'yellow fruit'}
    publish(path,show(first).encode())
    print('snapshot bytes:', path.stat().st_size)
    print('reopened:', show(json.loads(path.read_bytes())))
    broken=show({'apple':'red fruit','banana':'yellow fruit'}).encode()[:-3]
    write_sync(root/'dictionary.json.tmp',broken)
    try: json.loads((root/'dictionary.json.tmp').read_bytes())
    except json.JSONDecodeError: print('truncated candidate rejected; published apple:', json.loads(path.read_bytes())['apple'])
    first['apple']='red fruit'; publish(path,show(first).encode())
    print('replacement bytes:',path.stat().st_size,'; reopened apple:',json.loads(path.read_bytes())['apple'])

def mode_format(root):
    data=blob([(1,'é','tea')]); write_sync(root/'one.bin',data)
    row=parse((root/'one.bin').read_bytes())[0]
    print('hex:',data.hex())
    print('file header bytes: 4; record header bytes:',HEADER.size)
    print('key UTF-8 bytes:',len('é'.encode()),'; value bytes:',len('tea'.encode()),'; file bytes:',len(data))
    print('decoded:',show({'seq':row[0],'key':row[1],'value':row[2],'offset':row[3],'record_bytes':row[4]}))
    cases={'short_header':data[:6],'short_value':data[:-1],'invalid_length':data[:9]+b'\x00\x41'+data[11:],'unknown_version':b'F12\x02'+data[4:]}
    for name,damaged in cases.items():
        try: parse(damaged)
        except Corruption as error: print(name+' -> '+str(error))

def mode_versions(root):
    write_sync(root/'data-1.bin',blob([(1,'apple','fruit')]))
    publish(root/'CURRENT',b'data-1.bin')
    pins={}
    def acquire():
        name=(root/'CURRENT').read_text(); pins[name]=pins.get(name,0)+1
        return name
    def read(name): return resolved(parse((root/name).read_bytes()))['apple']
    old=acquire()
    write_sync(root/'data-2.bin',blob([(2,'apple','red fruit')]))
    sync_dir(root); publish(root/'CURRENT',b'data-2.bin')
    new=acquire()
    print('old reader:',old,read(old))
    print('new reader:',new,read(new))
    print('old file reclaimable:',str(pins[old] == 0).lower())
    pins[old]-=1
    if pins[old] == 0: (root/old).unlink()
    print('old reader released; old file exists:',str((root/old).exists()).lower())
    print('new reader after cleanup:',read(new))

def repair_unacknowledged_tail(data, acknowledged_end):
    # The caller must supply a trusted externally known complete acknowledgement boundary.
    prefix = data[:acknowledged_end]
    parse(prefix)
    try:
        parse(data)
    except TornTail:
        return prefix
    raise Corruption('repair requires a structurally incomplete tail')

def mode_log(root):
    path=root/'active.bin'; write_sync(path,MAGIC)
    for row in records(OPS[:5]): append_sync(path,row)
    good=path.read_bytes()
    print('complete records:',len(parse(good)),'; file bytes:',len(good),'; state:',show(resolved(parse(good))))
    torn=good+encode(6,'d','5')[:-1]; write_sync(path,torn)
    try: parse(path.read_bytes())
    except Corruption as error: print('strict reopen ->',str(error))
    repaired=repair_unacknowledged_tail(path.read_bytes(),len(good)); write_sync(path,repaired)
    print('known unacknowledged tail removed bytes:',len(torn)-len(repaired),'; state:',show(resolved(parse(path.read_bytes()))))
    bad=bytearray(good); bad[15+4]=9
    try: repair_unacknowledged_tail(bytes(bad),len(good))
    except Corruption as error: print('middle/header corruption ->',str(error))

def mode_bitcask(root):
    path=root/'active.bin'; write_sync(path,MAGIC)
    for row in records(OPS[:5]): append_sync(path,row)
    # Reopen reconstructs offsets, retaining no values in the directory.
    directory={}
    for seq,key,value,offset,size in parse(path.read_bytes()):
        if value is None: directory.pop(key,None)
        else: directory[key]=(offset,size)
    print('reopened keydir:',show(directory))
    reads=0
    def get(key):
        nonlocal reads
        location=directory.get(key)
        if location is None: return None,0
        offset,size=location
        with path.open('rb') as f:
            f.seek(offset); raw=f.read(size); reads+=1
        row,end=decode_one(raw,0)
        if len(raw) != size or end != size or row[1] != key or row[2] is None:
            raise Corruption('keydir location does not identify the requested live record')
        return row[2],len(raw)
    value,length=get('b')
    if value != '4': raise AssertionError('latest b was not read')
    print('get b: offset',directory['b'][0],'; bytes read',length,'; value',value)
    before=reads
    absent,_=get('a')
    if absent is not None or reads != before:
        raise AssertionError('deleted a must be absent without a data-file read')
    print('get a: absent; data file reads:',reads-before)
    print('retained file bytes:',path.stat().st_size,'; live keydir entries:',len(directory))

def lsm_states(compact_at=None):
    mem, runs, states = {}, [], []
    for row in records():
        mem[row[1]]=row
        if len(mem) == 3:
            runs.insert(0,sorted(mem.values(),key=lambda r:r[1])); mem={}
        if row[0] == compact_at:
            latest={}
            for run in reversed(runs):
                for item in run: latest[item[1]]=item
            runs=[[r for _,r in sorted(latest.items()) if r[2] is not None]]
        states.append({'step':row[0],'mem':sorted(mem.values(),key=lambda r:r[1]),'runs':[[list(x) for x in run] for run in runs], 'reads':{k:resolved([*mem.values(),*(r for run in runs for r in run)]).get(k) for k in 'abcdez'}})
    return mem,runs,states

def mode_lsm(root):
    _,runs,states=lsm_states()
    for state in states:
        print(show(state))
    for at in (6,9):
        _,_,alternative=lsm_states(at)
        print('compact_after_'+str(at)+':',show(alternative[at-1]))
        print('final_after_'+str(at)+':',show(alternative[-1]))

def mode_runs(root):
    _,runs,states=lsm_states()
    for name,run in zip(('R3','R2','R1'),runs): print(name+': '+show(run))
    print('final reads:',show(states[-1]['reads']))
    for at in (6,9):
        _,_,alternative=lsm_states(at)
        print('compact after '+str(at)+': '+show(alternative[at-1]['runs']))
    print('after compact at 6, then remaining edits: c='+show(lsm_states(6)[2][-1]['reads']['c']))

def recover(root):
    manifest=json.loads((root/'MANIFEST').read_bytes())
    rows=[]
    for name in manifest['files']: rows.extend(parse((root/name).read_bytes()))
    rows.extend(r for r in parse((root/'WAL').read_bytes()) if r[0]>manifest['checkpoint'])
    return manifest,resolved(rows)

def flush_child(root, boundary):
    mem={}
    for row in records(OPS[:3]):
        append_sync(root/'WAL',row)
        mem[row[1]]=row
    print('acknowledged through sequence 3',flush=True)
    if boundary == 'wal': os._exit(17)
    write_sync(root/'run-1.bin',blob(sorted(mem.values(),key=lambda r:r[1])))
    sync_dir(root)
    if boundary == 'table': os._exit(17)
    publish(root/'MANIFEST',show({'checkpoint':3,'files':['run-1.bin']}).encode())
    if boundary == 'manifest': os._exit(17)
    publish(root/'WAL',MAGIC)
    if boundary == 'retired_wal': os._exit(17)

def mode_flush(root):
    for boundary in ('wal','table','manifest','retired_wal'):
        case=root/boundary; case.mkdir()
        publish(case/'MANIFEST',show({'checkpoint':0,'files':[]}).encode()); write_sync(case/'WAL',MAGIC)
        child=subprocess.run([sys.executable,str(Path(__file__).resolve()),'_flush_child',str(case),boundary],capture_output=True,text=True)
        assert child.returncode == 17 and 'acknowledged through sequence 3' in child.stdout
        manifest,state=recover(case)
        print(boundary+': exit='+str(child.returncode)+' manifest='+show(manifest)+' WAL_bytes='+str((case/'WAL').stat().st_size)+' state='+show(state))

def bloom_positions(key):
    # Deliberately small filter: two independent salted SHA-256 reductions into eight bits.
    return [int.from_bytes(hashlib.sha256(s+key.encode()).digest()[:4],'big')%8 for s in (b'0',b'1')]

def make_reader(path,rows):
    write_sync(path,blob(rows)); data=path.read_bytes(); decoded=parse(data)
    keys=[r[1] for r in decoded]
    sparse=[(r[1],r[3]) for i,r in enumerate(decoded) if i%2 == 0]
    bits=set(p for k in keys for p in bloom_positions(k))
    return {'path':path,'min':min(keys),'max':max(keys),'sparse':sparse,'bits':bits,'length':len(data)}

def probe(run,key):
    if not run['min'] <= key <= run['max']: return 'range',None,0
    if not all(p in run['bits'] for p in bloom_positions(key)): return 'filter',None,0
    i=bisect.bisect_right([k for k,_ in run['sparse']],key)-1
    offset=run['sparse'][max(0,i)][1]; examined=0
    # Seek to a sparse anchor and decode through a match or the first larger key; count records, not OS blocks.
    with run['path'].open('rb') as f:
        if os.fstat(f.fileno()).st_size != run['length']:
            raise Corruption('probed file length differs from published metadata')
        if f.read(len(MAGIC)) != MAGIC:
            raise Corruption('unsupported probed file header')
        if not len(MAGIC) <= offset < run['length']:
            raise Corruption('sparse offset outside published file')
        f.seek(offset)
        while f.tell() < run['length']:
            header=f.read(HEADER.size)
            if len(header)!=HEADER.size: raise TornTail('short probed header')
            _,_,nk,nv=HEADER.unpack(header)
            if not 1 <= nk <= MAX_KEY or nv > MAX_VALUE: raise Corruption('invalid probed lengths')
            if f.tell()+nk+nv > run['length']: raise Corruption('record exceeds published file')
            row,_=decode_one(header+f.read(nk+nv),0); examined+=1
            if row[1]==key: return 'found' if row[2] is not None else 'tombstone',row[2],examined
            if row[1]>key: break
    return 'false-positive',None,examined

def mode_reads(root):
    rows=[(1,'a','1'),(2,'c','3'),(3,'e','5'),(4,'g','7'),(5,'i','9')]
    run=make_reader(root/'sparse.bin',rows)
    print('sparse offsets:',show(run['sparse']))
    print('filter set bits:',show(sorted(run['bits'])))
    for key in ('z','b','cc','g'):
        outcome,value,count=probe(run,key)
        print(key+': '+outcome+'; records_read='+str(count)+'; value='+show(value))
    old=make_reader(root/'old.bin',[(1,'a','1'),(2,'c','3')]); new=make_reader(root/'new.bin',[(3,'c',None)])
    visited=[]; total=0
    for candidate in (new,old):
        visited.append(candidate['path'])
        outcome,value,count=probe(candidate,'c'); total+=count
        if outcome in ('found','tombstone'): break
    older_opened=old['path'] in visited  # c passes both runs' range/filter checks.
    if outcome != 'tombstone' or value is not None or older_opened:
        raise AssertionError('newest deletion must stop lookup before the older run')
    print('newest c: '+outcome+'; records_read='+str(total)+'; older_run_opened='+show(older_opened))

def mode_compaction(root):
    _,runs,_=lsm_states()
    paths=[]
    for i,run in enumerate(runs):
        p=root/f'run{i}.bin';write_sync(p,blob(run));paths.append(p)
    before=sum(p.stat().st_size for p in paths)
    allrows=[r for p in paths for r in parse(p.read_bytes())]
    newest={}
    for row in allrows:
        if row[1] not in newest or row[0] > newest[row[1]][0]: newest[row[1]]=row
    merged=[r for _,r in sorted(newest.items()) if r[2] is not None]
    target=root/'merged.bin';write_sync(target,blob(merged));after=target.stat().st_size
    logical=sum(len(k.encode())+len(v.encode()) for k,v in OPS if v is not None)+sum(len(k.encode()) for k,v in OPS if v is None)
    print('input run bytes:',before,'; output run bytes:',after,'; peak input+output bytes:',before+after)
    print('logical submitted key/value bytes:',logical,'; flushed+compacted run bytes:',before+after)
    print('write ratio:',f'{before+after}/{logical} = {(before+after)/logical:.4f}')
    print('space ratio before/after:',f'{before}/{after} = {before/after:.4f}')
    def unfiltered_absence(selected):
        probes=0
        for path in selected:
            probes+=1
            assert all(row[1] != 'z' for row in parse(path.read_bytes()))
        return probes
    print('unfiltered run probes for absent z: before',unfiltered_absence(paths),'; after',unfiltered_absence([target]))
    # Compact only the newest run, wrongly dropping its c tombstone, leaves old c visible.
    wrong=[r for r in runs[0] if r[2] is not None]
    print('partial merge dropping c tombstone ->',show(resolved([*wrong,*(r for run in runs[1:] for r in run)]).get('c')))
    print('full merge state:',show(resolved(parse(target.read_bytes()))))

def mode_checksums(root):
    data=blob([(1,'a','1')]); protected=data+struct.pack('>I',zlib.crc32(data))
    good=root/'good.bin'; copy=root/'copy.bin';write_sync(good,protected);write_sync(copy,protected)
    damaged=bytearray(copy.read_bytes()); offset=14;damaged[offset]^=1;write_sync(copy,damaged)
    def verify(path):
        raw=path.read_bytes()
        if len(raw)<8 or zlib.crc32(raw[:-4])!=struct.unpack('>I',raw[-4:])[0]: raise Corruption('checksum mismatch')
        return parse(raw[:-4])
    print('protected bytes:',len(protected),'; CRC32:',format(zlib.crc32(data),'08x'))
    print('SHA-256:',hashlib.sha256(protected).hexdigest())
    print('flipped byte offset:',offset,'; before:',protected[offset],'; after:',damaged[offset])
    print('structural parse without checksum:',show(resolved(parse(bytes(damaged[:-4])))))
    try:verify(copy)
    except Corruption as error: print('protected read ->',error)
    verify(good)
    if hashlib.sha256(good.read_bytes()).digest()!=hashlib.sha256(protected).digest():
        raise Corruption('repair source differs from expected artifact')
    publish(copy,good.read_bytes());restored=verify(copy)
    if copy.read_bytes()!=protected: raise Corruption('repair destination differs from expected artifact')
    print('verified good copy restored:',show(resolved(restored)),'; SHA-256 equal:',str(hashlib.sha256(copy.read_bytes()).digest()==hashlib.sha256(good.read_bytes()).digest()).lower())

MODES={'api':mode_api,'tradeoffs':mode_tradeoffs,'snapshot':mode_snapshot,'format':mode_format,'versions':mode_versions,'log':mode_log,'bitcask':mode_bitcask,'lsm':mode_lsm,'runs':mode_runs,'flush':mode_flush,'reads':mode_reads,'compaction':mode_compaction,'checksums':mode_checksums}
if __name__=='__main__':
    if len(sys.argv)>1 and sys.argv[1]=='_flush_child':
        flush_child(Path(sys.argv[2]),sys.argv[3])
    elif len(sys.argv)!=2 or sys.argv[1] not in MODES:
        raise SystemExit('usage: python3 m12-storage-engine.py {'+','.join(MODES)+'}')
    else:
        with tempfile.TemporaryDirectory(prefix='fanout-m12-') as directory:
            MODES[sys.argv[1]](Path(directory))
