import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import tarfile

os.umask(0o077)
ROOT=Path('/backup/contextra/deployment-inbox/icerti-crowd-20260928-r01')
archive=Path('/home/si/icerti-crowd-20260928-r01.tar.gz')
assert hashlib.sha256(archive.read_bytes()).hexdigest()=='44b50b111eb7c1a35927b2ae5434d2a5328a3de08cd72b5b2c60631c1080709a'
assert not (ROOT/'kit').exists()
with tarfile.open(archive) as tar:tar.extractall(ROOT,filter='data')
kit=ROOT/'kit';manifest=json.loads((kit/'manifest.json').read_text())
for p,h in manifest['files'].items():assert hashlib.sha256((kit/p).read_bytes()).hexdigest()==h,p
def cmd(args,timeout=20):return subprocess.check_output(args,text=True,timeout=timeout)
def image(tag):return json.loads(cmd(['docker','image','inspect',tag]))[0]['Id']
images={}
for service,base,dockerfile,tag in [
    ('analytics','contextra-analytics:icerti-provider-d900910-20260927-r02','Analytics.Dockerfile','contextra-analytics:icerti-crowd-0f172d94-20260928-r01'),
    ('ai-control-sidecar','contextra-sidecar:icerti-provider-d900910-20260927-r01','Sidecar.Dockerfile','contextra-sidecar:icerti-crowd-0f172d94-20260928-r01')]:
    assert shutil.disk_usage('/').free>15*1024**3
    assert image(base)==manifest['base_images'][service]
    assert subprocess.run(['docker','image','inspect',tag],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=10).returncode!=0
    with (ROOT/('build-'+service+'.log')).open('x') as log:
        p=subprocess.run(['docker','build','--pull=false','--network=none','--memory=2g','--cpu-period=100000','--cpu-quota=200000',
            '-f',str(kit/dockerfile),'-t',tag,str(kit)],env=dict(os.environ,DOCKER_BUILDKIT='0'),stdout=log,stderr=log,timeout=180)
    assert p.returncode==0,'BUILD_'+service
    assert image(base)==manifest['base_images'][service]
    images[service]=dict(tag=tag,id=image(tag))
    print(json.dumps(dict(built=service,**images[service])),flush=True)
with (ROOT/'images.json').open('x') as f:json.dump(images,f,indent=2)
args=['docker','run','--rm','--pull=never','--runtime=runc','--network=none','--cpus=2','--memory=2g','--pids-limit=128',
    '-e','NVIDIA_VISIBLE_DEVICES=void','-e','PYTHONDONTWRITEBYTECODE=1','-e','PYTEST_DISABLE_PLUGIN_AUTOLOAD=1',
    '-v',str(kit)+':/verify:ro','-v',str(ROOT)+':/evidence','-w','/verify','--entrypoint','python3',images['analytics']['id'],
    '-B','-m','pytest','-q','-p','no:cacheprovider','--basetemp=/evidence/pytest-tmp',
    'tests/test_crowd_events.py','tests/test_event_cooldown.py','tests/test_secure_bridge_tls_gateway.py',
    '-k','not real_nginx and not outbound_transport and not tls_valid and not tls_rejects and not config_rejects']
with (ROOT/'targeted-tests.log').open('x') as log:
    p=subprocess.run(args,stdout=log,stderr=log,timeout=90)
print((ROOT/'targeted-tests.log').read_text()[-2500:])
assert p.returncode==0,'TARGETED_TESTS'
