"""Execute one real deque-backed variant and compare independent literal snapshots."""
from pathlib import Path
import argparse,collections,hashlib,inspect,json,marshal,platform,sys,time
import implementation as impl
BASE=Path(__file__).resolve().parent

def exact(a,b):
    if type(a) is not type(b): return False
    if isinstance(a,dict): return a.keys()==b.keys() and all(exact(a[k],b[k]) for k in a)
    if isinstance(a,list): return len(a)==len(b) and all(exact(x,y) for x,y in zip(a,b))
    return a==b

def main():
    p=argparse.ArgumentParser();p.add_argument('--variant',choices=['baseline','corrected','reject-all'],required=True);a=p.parse_args()
    expected=json.loads((BASE/'expected.json').read_text());events=expected['payloads'];entries=[];pending={};source=(BASE/'implementation.py').read_bytes();source_sha=hashlib.sha256(source).hexdigest()
    allowed={'QueueCore.__init__','QueueCore.join','QueueCore.drain','Baseline.publish','Corrected.publish','RejectAllControl.publish'}
    def profile(frame,event,arg):
        code=frame.f_code
        if Path(code.co_filename).resolve()!=BASE/'implementation.py' or code.co_qualname not in allowed:return
        if event=='call':
            values={}
            for name in ['capacity','consumer_id','message_id','payload']:
                if name in frame.f_locals:
                    value=frame.f_locals[name];values[name]={'bytes_hex':value.hex()} if type(value) is bytes else value
            row={'entry':len(entries)+1,'function':code.co_qualname,'selfClass':type(frame.f_locals['self']).__name__,'sourceFile':'implementation.py','sourceLine':code.co_firstlineno,'fileSha256':source_sha,'functionSourceSha256':hashlib.sha256(inspect.getsource(code).encode()).hexdigest(),'runtimeCodeObjectSha256':hashlib.sha256(marshal.dumps(code)).hexdigest(),'arguments':values}
            entries.append(row);pending[id(frame)]=row
        elif event=='return':
            row=pending.pop(id(frame));row['return']=arg
    def consumer_state(c):
        assert type(c.queue) is collections.deque
        return {'generation':c.generation,'active':c.active,'close_reason':c.close_reason,'queue':[{'id':x,'payload_hex':payload.hex()} for x,payload in c.queue],'queued_messages':len(c.queue),'queued_payload_bytes':sum(len(payload) for _,payload in c.queue)}
    frames=[];delivered={'healthy':[],'slow':[]};retired=None
    def snapshot(label,receipt):
        frames.append({'label':label,'receipt':receipt,'consumers':{name:consumer_state(c) for name,c in broker.consumers.items()},'delivered':{name:list(values) for name,values in delivered.items()},'retired_slow':None if retired is None else consumer_state(retired)})
    variants={'baseline':impl.Baseline,'corrected':impl.Corrected,'reject-all':impl.RejectAllControl}
    before=sys.getprofile();start=time.perf_counter_ns();sys.setprofile(profile)
    try:
        broker=variants[a.variant](capacity=3)
        healthy=broker.join('healthy');slow=broker.join('slow');snapshot('ready',{'healthy':healthy,'slow':slow})
        for item in events[:6]:
            receipt=broker.publish(item['id'],bytes.fromhex(item['payload_hex']));snapshot('publish-'+str(item['id']),receipt)
            receipt=broker.drain('healthy');delivered['healthy'].extend(receipt['messages']);snapshot('healthy-drain-'+str(item['id']),receipt)
        retired=broker.consumers['slow'];receipt=broker.join('slow');snapshot('slow-rejoin',receipt)
        item=events[6];receipt=broker.publish(item['id'],bytes.fromhex(item['payload_hex']));snapshot('publish-7',receipt)
        receipt=broker.drain('healthy');delivered['healthy'].extend(receipt['messages']);snapshot('healthy-drain-7',receipt)
        receipt=broker.drain('slow');delivered['slow'].extend(receipt['messages']);snapshot('slow-drain-7',receipt)
    finally:sys.setprofile(before)
    elapsed=time.perf_counter_ns()-start
    matches=[{'label':e['label'],'matchesLiteral':exact(e,v)} for e,v in zip(expected['snapshots'],frames)]
    assert len(matches)==len(frames)==len(expected['snapshots'])==17 and not pending
    counts={name:sum(row['function'].endswith('.'+name) for row in entries) for name in ['__init__','join','publish','drain']}
    trace_ok=counts=={'__init__':1,'join':3,'publish':7,'drain':8} and len(entries)==19
    bounds=all(c['queued_messages']<=3 and c['queued_payload_bytes']<=12 for f in frames for c in f['consumers'].values())
    maxima={name:{'messages':max(f['consumers'][name]['queued_messages'] for f in frames),'logicalPayloadBytes':max(f['consumers'][name]['queued_payload_bytes'] for f in frames)} for name in ['healthy','slow']}
    max_total=max(sum(c['queued_payload_bytes'] for c in f['consumers'].values()) for f in frames)
    accepted=all(row['matchesLiteral'] for row in matches) and trace_ok
    report={'variant':a.variant,'runtime':sys.version,'platform':platform.platform(),'executionElapsedNs':elapsed,'measurementScope':'One finite deterministic single-thread schedule; logical queued payload/count snapshots only, not RSS/heap/rate/concurrency/transport evidence.','sourceFileSha256':source_sha,'expectedFileSha256':hashlib.sha256((BASE/'expected.json').read_bytes()).hexdigest(),'entryInstrumentation':'sys.setprofile on six explicitly named real implementation methods; no every-function/branch/coverage claim. runtimeCodeObjectSha256 is interpreter/path specific.','methodEntries':entries,'actualSelectedMethodEntryCounts':counts,'constructorEntries':1,'initialJoinEntries':2,'explicitRejoinEntries':1,'publishEntries':7,'healthyDrainEntries':7,'slowDrainEntries':1,'observedSnapshots':frames,'literalComparisons':matches,'matchingSnapshots':sum(row['matchesLiteral'] for row in matches),'snapshotCount':17,'traceEntryGate':trace_ok,'weakerResourceOnlyGate':bounds,'strongContractGate':accepted,'maxPerConsumer':maxima,'maximumTotalQueuedLogicalPayloadBytesAcrossTwoCurrentQueues':max_total,'finalDelivered':delivered,'noResidualRiskAcceptance':True}
    print(json.dumps(report,indent=2));return 0 if accepted else 1
if __name__=='__main__':raise SystemExit(main())
