import json
import os
from pathlib import Path
import shutil
import sys
import tarfile
import time

os.umask(0o077)
R=Path(__file__).parent
sys.path.insert(0,'/tmp/codex/ltb1021/2026-09-13_contextra-fire-intake_r01')
from inspect_intake import gate as g, state, WEIGHT
from model_tooling.manifests import make_input,write_new_yaml,validate_input,fingerprints
assert json.loads((R/'export-result.json').read_text())['status']=='CONTRACT_PASS'
assert json.loads((R/'engine-verify-run.json').read_text())['status']=='PASS'
assert json.loads((R/'cas-test.json').read_text())==dict(tests=1,failures=0,errors=0)
manifest=make_input('fire-smoke-medium-v110-strict-v1',WEIGHT)
target=WEIGHT.parent/'manifest.yaml'
write_new_yaml(target,manifest)
assert validate_input(target)==manifest
deployment=Path('/data/contextra/model-artifacts/builds/fire-smoke-193-20260913-r01')
assert shutil.disk_usage(deployment.parent).free>=15*1024**3
deployment.mkdir(mode=0o700)
export=json.loads((R/'export-result.json').read_text())
artifacts={}
for source,name in [(R/'export'/Path(export['onnx']['path']).name,'model.onnx'),(R/'fire.plan','model.plan'),(target,'input-manifest.yaml')]:
    dest=deployment/name
    with source.open('rb') as src,dest.open('xb') as dst:shutil.copyfileobj(src,dst)
    assert g.sha(dest)==g.sha(source)
    artifacts[name]=fingerprints(dest)
paths=g.sh(['git','-C',str(g.REPO),'ls-files','-c','-o','--exclude-standard']).splitlines()
paths=sorted({p for p in paths if p.startswith(('app/','native/','model_tooling/','tests/')) and (g.REPO/p).is_file()})
hashes={p:g.sha(g.REPO/p) for p in paths}
with tarfile.open(R/'source-snapshot.tar.gz','w:gz') as tar:
    for path in paths:tar.add(g.REPO/path,arcname=path,recursive=False)
(R/'source-snapshot.json').write_text(json.dumps(dict(head=g.sh(['git','-C',str(g.REPO),'rev-parse','HEAD']).strip(),files=hashes,tar_sha256=g.sha(R/'source-snapshot.tar.gz')),indent=2))
before=json.loads((R/'before.private.json').read_text());after=state()
for key in ('container_id','image','restart','streams_stopped','hashes','others'):
    assert before[key]==after[key],key
assert sorted(before['mounts'],key=lambda m:m['Destination'])==sorted(after['mounts'],key=lambda m:m['Destination'])
leftovers=[s for s in g.sh(['docker','ps','-a','--format','{{.Names}}']).splitlines() if s.startswith('codex-ltb1021-fire-')]
assert not leftovers
(R/'after.private.json').write_text(json.dumps(after,indent=2))
summary=dict(manifest=str(target),artifact_directory=str(deployment),artifacts=artifacts,
             load='PASS_SAFE_193_NO_MISSING_OR_UNEXPECTED_KEYS',onnx='PASS_CONTRACT_AND_NUMERICAL',
             fp16='PASS_SHAPE_FINITE; NUMERICAL_FAIL',comparison=json.loads((R/'comparison.json').read_text()),
             source='NATIVE_COMPILE_AND_ORACLE_PASS; 66/67 tests PASS then corrected standalone CAS 1/1 PASS',
             model_experiments=dict(cpu_reference=1,onnx_export=1,fp16_build=1,plan_execution=1),
             actual_runtime='NOT_RUN',image_build=0,deploy=0,stream_start=0,
             current='healthy/Stream stopped',service_unchanged=True,
             gpu_before_mib=before['gpu_mib'],gpu_after_mib=after['gpu_mib'],task_containers=0,
             rights='UNVERIFIED; user-approved internal test; not commercial clearance',
             next='Approved video quality review; image-owned SDK Fire boundary validation; bounded Runtime later')
(R/'summary.json').write_text(json.dumps(summary,indent=2))
(deployment/'validation.json').write_text(json.dumps(summary,indent=2))
ledger=json.loads((R/'ledger.json').read_text())
ledger.update(status='COMPLETE_SOURCE_PREPARATION',finished_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),
              failures=3,notes=['initial GPU-none SDK import lacked driver lib',
                 'inherited fixture omitted AL Off', 'late runtime spec edit did not update config SOT; stopped this approach',
                 'new persisted fixture verified one CAS test; no further model export/build'],plan_execution=1)
(R/'ledger.json').write_text(json.dumps(ledger,indent=2))
for p in R.rglob('*'):
    if p.is_file():p.chmod(0o600)
print(json.dumps({k:summary[k] for k in ('load','onnx','fp16','source','service_unchanged','gpu_before_mib','gpu_after_mib','task_containers','artifact_directory')}))
