import hashlib
import io
import json
import os
from pathlib import Path
import resource
import subprocess
import sys
import tarfile

ROOT = Path(__file__).resolve().parent.parent
REPO = Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
TMP = Path('/tmp/codex/ltb1021/2026-11-03_offline-export_r01')
LABEL = sys.argv[1] if len(sys.argv)>1 else 'r01'
TMP = TMP/LABEL
TMP.mkdir(mode=0o700,exist_ok=False)
sys.path.insert(0, str(REPO))
from deployment_kit.core import write_json
from export_images import verify_archive


def limits():
    cpus = sorted(os.sched_getaffinity(0))[:2]
    os.sched_setaffinity(0, cpus)
    resource.setrlimit(resource.RLIMIT_AS, (8*1024**3, 8*1024**3))


with (ROOT/f'reports/operator-tests-{LABEL}.log').open('xb') as stream:
    p = subprocess.run(['/root/miniconda3/envs/ssims-ai-tests/bin/python', '-m', 'pytest', '-q',
                        '-p', 'no:cacheprovider', '--basetemp', str(TMP/'pytest-final'),
                        '--junitxml', str(ROOT/f'reports/operator-tests-{LABEL}.xml'),
                        'tests/deployment/test_offline_operator.py', 'tests/deployment/test_image_export.py'],
                       cwd=REPO, env={**os.environ, 'PYTHONDONTWRITEBYTECODE':'1'}, preexec_fn=limits,
                       stdout=stream, stderr=subprocess.STDOUT, timeout=180)
assert p.returncode == 0

# Exercise the no-extract verifier with a self-contained synthetic Docker archive.
layer = b'synthetic layer payload'
lh = hashlib.sha256(layer).hexdigest()
cfg = json.dumps({'rootfs':{'type':'layers','diff_ids':['sha256:'+lh]}}).encode()
ident = 'sha256:'+hashlib.sha256(cfg).hexdigest()
name = ident.removeprefix('sha256:')+'.json'
manifest = json.dumps([{'Config':name,'RepoTags':None,'Layers':['layer/layer.tar']}]).encode()
fixture = TMP/'archive-fixture.tar'
with tarfile.open(fixture, 'x') as archive:
    for member, value in [(name,cfg),('layer/layer.tar',layer),('manifest.json',manifest)]:
        info = tarfile.TarInfo(member); info.size = len(value)
        archive.addfile(info, io.BytesIO(value))
checked = verify_archive(fixture, ident, {'RootFS':{'Layers':['sha256:'+lh]}})
assert checked['sha256'] == hashlib.sha256(fixture.read_bytes()).hexdigest()
write_json(ROOT/f'reports/operator-validation-{LABEL}.json', dict(pytest_exit_code=p.returncode, cpu_limit=2,
           memory_limit_gib=8, docker_mock_only=True, archive_fixture=checked),new=True)
print((ROOT/f'reports/operator-tests-{LABEL}.log').read_text())
print('ARCHIVE_FIXTURE_PASS')
