"""One bounded campaign. Wrapper success means expected contrasts reproduced."""
from pathlib import Path
from datetime import datetime,timezone
import argparse,hashlib,json,platform,sqlite3,subprocess,sys
import importer
BASE=Path(__file__).resolve().parent
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
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 save(p,data):p.write_text(json.dumps(data,indent=2)+'\n')
def snapshot(db):
    # A separate observer connection, not the import connection or a cached count.
    c=sqlite3.connect('file:'+db.as_posix()+'?mode=rw',uri=True,isolation_level=None,
                      autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)
    try:
        state={'records':[dict(zip(['source_revision','item_id','payload'],r)) for r in c.execute('SELECT source_revision,item_id,payload FROM records ORDER BY source_revision,item_id,payload')],
               'checkpoints':[dict(zip(['source_revision','next_index'],r)) for r in c.execute('SELECT source_revision,next_index FROM checkpoints ORDER BY source_revision')]}
        config={'isolation_level':c.isolation_level,'autocommit':c.autocommit,'journal_mode':c.execute('PRAGMA journal_mode').fetchone()[0],'synchronous':c.execute('PRAGMA synchronous').fetchone()[0],'in_transaction':c.in_transaction,'sqlite_version':sqlite3.sqlite_version}
        return state,config
    finally:c.close()
def main():
    p=argparse.ArgumentParser();p.add_argument('--output',required=True);a=p.parse_args();out=Path(a.output).resolve();out.mkdir(parents=True,exist_ok=False)
    files=['importer.py','run_child.py','source.json','CONTRACT.md','inventory.json','expected.json','reproduce.py'];before={name:sha(BASE/name) for name in files}
    oracle=json.loads((BASE/'expected.json').read_text());source=json.loads((BASE/'source.json').read_text());reports=[];commands=[];started=datetime.now(timezone.utc).isoformat()
    for variant,scenario in [('baseline','normal'),('baseline','recovery'),('corrected','normal'),('corrected','recovery'),('no-op','normal')]:
        name=variant+'-'+scenario;work=out/name;work.mkdir();db=work/'state.sqlite';setup=importer.initialize(str(db),variant);states=[];responses=[];entries=[]
        def observe(label,expected_state):
            state,settings=snapshot(db);states.append({'label':label,'state':state,'observerConnectionSettings':settings,'matchesLiteral':exact(state,oracle['states'][expected_state])});save(work/'observations.json',states)
        observe('setup','initial')
        for step in (['run'] if scenario=='normal' else ['interrupted','restart','repeat']):
            trace=work/(step+'.trace.jsonl');marker=work/(step+'.marker.json');argv=[sys.executable,'-B',str(BASE/'run_child.py'),'--variant',variant,'--db',str(db),'--trace',str(trace)]
            if step=='interrupted':argv+=['--stop-marker',str(marker)]
            start=datetime.now(timezone.utc).isoformat();child=subprocess.Popen(argv,cwd=BASE,stdout=subprocess.PIPE,stderr=subprocess.PIPE);stdout,stderr=child.communicate(timeout=30)
            (work/(step+'.stdout.json')).write_bytes(stdout);(work/(step+'.stderr.txt')).write_bytes(stderr)
            cmd={'case':name,'step':step,'argv':argv,'cwd':str(BASE),'pid':child.pid,'startedAtUtc':start,'finishedAtUtc':datetime.now(timezone.utc).isoformat(),'exitCode':child.returncode,'stdoutSha256':hashlib.sha256(stdout).hexdigest(),'stderrSha256':hashlib.sha256(stderr).hexdigest(),'traceSha256':sha(trace)};commands.append(cmd);save(out/'commands.json',commands)
            assert not stderr,(name,step,'unexpected stderr')
            trace_rows=[json.loads(line) for line in trace.read_text().splitlines()];public_name={'baseline':'baseline_import','corrected':'corrected_import','no-op':'no_op_import'}[variant]
            calls=[r for r in trace_rows if r['event']=='call' and r['function']==public_name];assert len(calls)==1
            assert calls[0]['fileSha256']==before['importer.py']
            assert exact(calls[0]['arguments'],{'path':str(db),'source_revision':source['source_revision'],'items':source['items']})
            entries.extend(trace_rows)
            if step=='interrupted':
                assert child.returncode==86 and stdout==b'' and exact(json.loads(marker.read_text()),oracle['interruption']['marker'])
                assert not any(r['event']=='return' and r['function']==public_name for r in trace_rows)
                responses.append({'step':step,'responseReturned':False,'exitCode':86,'matchesLiteral':True,'note':'No product response returned by abruptly terminated process.'});observe(step,'interrupted')
            else:
                assert child.returncode==0
                record=json.loads(stdout);expected_response=oracle['responses']['normal' if step=='run' else step]
                responses.append({'step':step,'responseReturned':True,'actual':record['response'],'expected':expected_response,'matchesLiteral':exact(record['response'],expected_response),'runtime':{'python':record['python'],'sqlite':record['sqlite']}});observe(step,'complete')
        final=states[-1]['state'];identities=[(r['source_revision'],r['item_id']) for r in final['records']];no_duplicates=len(identities)==len(set(identities))
        strong=all(r['matchesLiteral'] for r in states+responses)
        expected_pass=not (variant=='no-op' or variant=='baseline' and scenario=='recovery');assert strong is expected_pass,(name,'unexpected contract verdict',strong)
        public_entries=sum(r['event']=='call' and r['function'] in ['baseline_import','corrected_import','no_op_import'] for r in entries)
        shared_entries=sum(r['event']=='call' and r['function']=='_apply' for r in entries)
        connection_settings=[r['returnConnectionSettings'] for r in entries if 'returnConnectionSettings' in r]
        nominal={'R-ROWS':exact(final['records'],oracle['states']['complete']['records']),'R-COMPLETE':exact(final['checkpoints'],oracle['states']['complete']['checkpoints']) and responses[-1]['matchesLiteral']} if scenario=='normal' else None
        report={'case':name,'variant':variant,'scenario':scenario,'setupConnectionSettings':setup,'actualImportConnectionSettings':connection_settings,'observations':states,'responseObservations':responses,'recordedPublicImporterEntries':public_entries,'recordedSharedApplyEntries':shared_entries,'actualNewChildProcesses':len(responses),'selectedFullContractGate':strong,'weakerNoDuplicateOnlyGate':no_duplicates,'manualAuthoredNormalRequirementResults':nominal,'method':'Selected exact source public/helper/connection call-return profiling plus separate reopened observer connections. Not every-function/branch coverage or a native Proof audit.','runtime':sys.version,'sqlite':sqlite3.sqlite_version}
        save(work/'report.json',report);reports.append(report)
    after={name:sha(BASE/name) for name in files};assert before==after
    totals={'freshDatabases':len(reports),'selectedScenarios':len(reports),'sourceItems':len(source['items']),'initialAuthoredRequirementIds':2,'newAuthoredRequirementIdsTotal':3,'actualImporterCalls':sum(r['recordedPublicImporterEntries'] for r in reports),'sharedApplyEntries':sum(r['recordedSharedApplyEntries'] for r in reports),'actualChildProcesses':len(commands),'injectedStopsExit86':sum(c['exitCode']==86 for c in commands),'normalChildExits0':sum(c['exitCode']==0 for c in commands),'completeStateObservations':sum(len(r['observations']) for r in reports),'returnedProductResponses':sum(x['responseReturned'] for r in reports for x in r['responseObservations']),'selectedScenarioPasses':sum(r['selectedFullContractGate'] for r in reports)}
    result={'startedAtUtc':started,'finishedAtUtc':datetime.now(timezone.utc).isoformat(),'runtime':sys.version,'platform':platform.platform(),'sqlite':sqlite3.sqlite_version,'sourceAndInputsSha256':before,'sourceAndInputsUnchanged':True,'totals':totals,'cases':[{k:r[k] for k in ['case','recordedPublicImporterEntries','recordedSharedApplyEntries','selectedFullContractGate','weakerNoDuplicateOnlyGate','manualAuthoredNormalRequirementResults']} for r in reports],'wrapperExitCode':0,'wrapperExitMeaning':'Expected baseline-recovery and no-op failures plus selected correction acceptance reproduced. Does not accept faulty variants, complete stakeholder intent, run Proof, validate wider storage/concurrency policy or approve a Change/release.','solePrimaryCampaign':True,'durabilityBoundary':'Real committed local SQLite row observed from new connections after deliberate child os._exit86 and new-process restart; not power-loss/disk-full/fsync/concurrency proof.'}
    save(out/'summary.json',result);print(json.dumps(result));return 0
if __name__=='__main__':raise SystemExit(main())
