"""Run one frozen original native case once, preserving all first output bytes."""
import datetime, hashlib, json, subprocess, sys, time
from pathlib import Path

ROOT=Path(__file__).resolve().parent
sha=lambda raw:hashlib.sha256(raw).hexdigest()
load=lambda p:json.loads(p.read_bytes())
put=lambda p,v:p.open('xb').write((json.dumps(v,ensure_ascii=False,indent=2)+'\n').encode())
runtime_path=ROOT/'runtime-frozen-v1.json'
runtime=load(runtime_path)
runtime_sha=sha(runtime_path.read_bytes())
review=load(ROOT.parent.parent/'reviews/fabric-addition-2026-10-03/preflight/runtime-review-v1.json')
assert review['passed'] and review['runtimeSha256']==runtime_sha
assert sha(Path(__file__).read_bytes())==runtime['runnerSha256']
assert len(sys.argv)==2
cid=sys.argv[1]
case=next(c for c in runtime['cases'] if c['id']==cid)
state=load(ROOT/'private/recorder-state.json')
assert state['pid']==runtime['recorderPid'] and state['port']==runtime['recorderPort']
assert state['inFlight']==0 and state['cases'][cid]['forwards']==0
assert not (ROOT/'private/armed-case.json').exists()
assert not Path(case['outputPath']).exists()
for row in runtime['officialFiles']:
    assert sha(Path(row['path']).read_bytes())==row['sha256']
assert sha(Path(runtime['childEnvironmentPath']).read_bytes())==runtime['childEnvironmentSha256']
assert sha(Path(runtime['dotenvPath']).read_bytes())==runtime['dotenvSha256']
assert sha((ROOT/'original-case-contract-v1.json').read_bytes())==runtime['contractSha256']
assert sha((ROOT/'native-recorder-v1.py').read_bytes())==runtime['recorderSha256']
raw=Path(case['inputPath']).read_bytes()
assert sha(raw)==case['inputSha256']
RUNS=ROOT/'runs'
RUNS.mkdir(exist_ok=True)
marker=RUNS/(cid+'-attempt.json')
start=time.time()
put(marker,{'caseId':cid,'attemptedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'nativeAttemptOrdinal':1,'runtimeSha256':runtime_sha})
arm=ROOT/'private/armed-case.json'
put(arm,{'caseId':cid,'runtimeSha256':runtime_sha,'startedAtEpoch':start,'deadlineEpoch':start+180})
proc=None
timedout=False
error=None
try:
    with (RUNS/(cid+'-stdout.bin')).open('xb') as out, (RUNS/(cid+'-stderr.bin')).open('xb') as err:
        proc=subprocess.Popen(case['argv'],cwd=case['cwd'],env=load(Path(runtime['childEnvironmentPath'])),stdin=subprocess.PIPE,stdout=out,stderr=err)
        try: proc.communicate(raw,timeout=max(0.001,start+180-time.time()))
        except subprocess.TimeoutExpired:
            timedout=True
            proc.kill()
            proc.communicate()
except Exception as exc:
    error=type(exc).__name__
finally:
    arm.unlink(missing_ok=True)
output=Path(case['outputPath'])
if output.exists():
    copied=RUNS/(cid+'-first-native-output.md')
    with copied.open('xb') as stream: stream.write(output.read_bytes())
receipt={'caseId':cid,'startedAtEpoch':start,'completedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'durationMs':round((time.time()-start)*1000),'nativeAttemptCount':1,'nativeProcessCount':int(proc is not None),'nativePid':proc.pid if proc else None,'exitCode':proc.returncode if proc else None,'timeout':timedout,'errorType':error,'outputExists':output.exists(),'outputBytes':output.stat().st_size if output.exists() else 0,'outputSha256':sha(output.read_bytes()) if output.exists() else None,'runtimeSha256':runtime_sha,'providerForwardsAtReturn':load(ROOT/'private/recorder-state.json')['cases'][cid]['forwards'],'manualQualityReruns':0,'manualOutputRepairs':0,'recorderArmedAfterProcess':arm.exists()}
put(RUNS/(cid+'-process.json'),receipt)
print(json.dumps(receipt))
