"""Bounded read-only site snapshot; no credentials or input URI in output."""
import base64
import importlib.util
import json
import os
from pathlib import Path

ROOT = Path(__file__).resolve().parent
os.umask(0o077)
sp = importlib.util.spec_from_file_location('remote', ROOT.parent/'2026-11-01_icerti-fight-r5_r01/remote.py')
r = importlib.util.module_from_spec(sp)
sp.loader.exec_module(r)
NAMES = ['app/fall_runtime.py', 'app/stream_settings.py', 'app/fall_r2/config.py',
         'app/fall_r2/web.py', 'app/fall_r2/core.py', 'app/fall_r2/runtime.py']
CODE = '''import json,sys,subprocess,shutil,os
from pathlib import Path
d=json.loads(Path('/etc/contextra-maintenance/server.json').read_text())
assert d['server']=='icerti-ai2'
assert shutil.disk_usage('/').free>=15*1024**3
sys.path.insert(0,d['paths']['tools']);import compose_backend as cb
rows={x['Config']['Labels']['com.docker.compose.service']:x for x in cb.containers()}
script="""import os,json,base64,hashlib,urllib.request,yaml
from pathlib import Path
token=Path(os.environ['CONTEXTRA_CONTROL_TOKEN_FILE']).read_text().strip()
q=urllib.request.Request('http://127.0.0.1:5000/internal/secure-control/runtime-status',headers={'Authorization':'Bearer '+token})
with urllib.request.urlopen(q,timeout=5) as response:runtime=json.load(response)
root=Path('/opt/contextra')
files={n:base64.b64encode((root/n).read_bytes()).decode() for n in NAMES}
guard_names=[str(p.relative_to(root)) for p in (root/'app/fight_r5').glob('*') if p.suffix in ('.py','.json')]
guard_names+=['app/fight_runtime.py','app/byte_tracking.py','app/fall_r2/base.json','app/fall_r2/rules.json','app/fall_r2/reference.py','app/fall_r2/decision.py','app/fall_r2/geometry.py']
guards={n:hashlib.sha256((root/n).read_bytes()).hexdigest() for n in guard_names}
configs={}
for key in ('CONTEXTRA_CONTROL_TEMPLATE_FILE','STREAMS_CONFIG_PATH','STREAMS_RUNTIME_PATH'):
 p=Path(os.environ[key]);raw=p.read_bytes();v=json.loads(raw) if p.suffix=='.json' else yaml.safe_load(raw)
 items=[v] if key=='CONTEXTRA_CONTROL_TEMPLATE_FILE' else v.get('added',v.get('streams',[]))
 configs[key]=dict(sha256=hashlib.sha256(raw).hexdigest(),channels=[dict(camera=x.get('camera_id',x.get('source_id')),stream=x.get('stream_id'),fall=x.get('fall'),fight=x.get('fight'),cooldown=x.get('event_cooldowns')) for x in items])
print(json.dumps(dict(files=files,guards=guards,configs=configs,runtime_counts=runtime.get('streamCounts'),streams=[{k:s.get(k) for k in ('streamId','cameraId','state','runId','runGeneration')} for s in runtime.get('streams',[])])))
""".replace('NAMES',repr(NAMES))
p=subprocess.run(['docker','exec','-i',rows['analytics']['Id'],'python3','-B','-'],input=script.encode(),capture_output=True,timeout=40)
assert p.returncode==0,'Bounded preflight failed; preserve stderr privately for review'
v=json.loads(p.stdout)
v['containers']={k:dict(id=x['Id'],image=x['Image'],running=x['State']['Running'],health=x['State'].get('Health',{}).get('Status')) for k,x in rows.items()}
v['images']={k:x['Image'] for k,x in rows.items()};v['free_root']=shutil.disk_usage('/').free;v['active']=cb.active()
v['resources']=dict(cpus=os.cpu_count(),loadavg=os.getloadavg(),mem_available_kib=int(next(l.split()[1] for l in Path('/proc/meminfo').read_text().splitlines() if l.startswith('MemAvailable:'))))
print(json.dumps(v))
'''.replace('repr(NAMES)', repr(repr(NAMES)))

if __name__ == '__main__':
    assert not (ROOT/'preflight.json').exists()
    value = json.loads(r.python(CODE, sudo=True, timeout=65))
    (ROOT/'preflight.json').write_text(json.dumps(value, indent=2))
    for name, encoded in value['files'].items():
        path = ROOT/'site_source'/name
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(base64.b64decode(encoded))
    print(json.dumps(dict(runtime_counts=value['runtime_counts'],resources=value['resources'],
        free_root_gib=round(value['free_root']/1024**3,1),containers=value['containers'],
        config_counts={k:len(v['channels']) for k,v in value['configs'].items()}),indent=2))
