import datetime
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys

ROOT = Path(__file__).resolve().parent.parent
REPO = Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
PRIOR = ROOT.parent/'2026-11-03_contextra-offline-full-prep_r01'
DELIVERY = ROOT/'Contextra_Offline_Preparation_20261103_r02'
sys.path.insert(0,str(REPO))
from deployment_kit.core import lock,sha256,write_json
from prepare_evidence import snapshot

baseline=json.loads((ROOT/'reports/r02/export-baseline.json').read_bytes())
after=snapshot()
assert baseline['containers']==after['containers'] and baseline['files']==after['files']
progress=json.loads((ROOT/'reports/r02/export-progress.json').read_bytes())
assert progress['status']=='COMPLETE' and len(progress['completed'])==6
assert not list((DELIVERY/'images').glob('.tmp-*'))
with lock(Path('/tmp/codex/ltb1021/2026-11-03_offline-export_r01/export-lock')):
    pass
seal=subprocess.run([sys.executable,str(ROOT/'helpers/seal_ready.py')],capture_output=True,text=True,timeout=120)
assert seal.returncode==2 and 'SOURCE_DIRTY' in seal.stdout
assert not (ROOT/'Contextra_Offline_Test_20261103_Sealed').exists()
validation=dict(timestamp=datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).isoformat(),
                archives=6,total_bytes=sum(r['bytes'] for r in progress['completed']),
                min_root_free=min(r['min_root_free'] for r in progress['completed']),
                final_root_free=after['free']['/'],running_containers=sum(c['running'] for c in after['containers']),
                all_container_records_unchanged=True,config_file_fingerprints_unchanged=True,
                root_cleanup_reclaimed=json.loads((ROOT/'reports/cleanup-result.json').read_bytes())['reclaimed'],
                root_floor_gib=10,root_stop_gib=12,temporary_archive_files_remaining=0,export_lock_released=True,
                source_seal_exit_code=seal.returncode,source_seal_gate=json.loads(seal.stdout),
                pytest_final='55 passed',live_export_source_sha256=sha256(ROOT/'reports/source-snapshot/image_export.py'),
                final_source_sha256=sha256(REPO/'deployment_kit/offline/image_export.py'),
                live_export_note='6 archives used the preserved source snapshot; afterward temporary-output diagnostics and iterator tests were hardened without replaying save',
                windows_copy=False,usb_copy=False,runtime_applied=False,fps_acceptance=False,cold_load_test=False)
write_json(ROOT/'reports/final-validation.json',validation,new=True)
write_json(ROOT/'reports/final-snapshot.json',after,new=True)
for name in ('final-validation.json','source-lock.json','locations.json'):
    shutil.copyfile(ROOT/'reports'/name,DELIVERY/name)
refs=DELIVERY/'references';refs.mkdir(mode=0o700)
for name in ('candidate-image.json','image-source-check.json','deployed-core-comparison.json'):
    shutil.copyfile(PRIOR/name,refs/name)
print(json.dumps(validation,ensure_ascii=False,indent=2))
