import contextlib, ctypes, glob, hashlib, json, os, pathlib, subprocess, sys, unittest
R = pathlib.Path('/evidence')
os.umask(0o077)
assert not glob.glob('/dev/nvidia*')
os.environ['DATABASE_URL'] = 'postgresql://u:p' + chr(64) + 'localhost:1/db'
os.environ['REDIS_STREAMS_ENABLED'] = 'false'
os.environ['TMPDIR'] = '/evidence'
sys.path.append('/tool-overlay')
mode = sys.argv[1]
if mode == 'image':
    expected = json.loads((R/'source-hashes.json').read_text())
    assert all(hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest() == h for p,h in expected.items())
    for name,symbol in [('libcontextra_nvinferserver_rfdetr.so','CreateContextraRfDetrProcessor'), ('libcontextra_medium_preprocess.so','CustomTensorPreparation')]:
        assert getattr(ctypes.CDLL('/opt/contextra/lib/'+name), symbol)
with (R/(mode+'-tests.log')).open('w') as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
    subprocess.run(['python3','tests/sdk_stop_observation_probe.py'], check=True, timeout=25, stdout=log, stderr=log)
    suite = unittest.TestSuite()
    for pattern in ['test_stop_observation.py', 'test_cleanup_boundary.py', 'test_start_diagnostics.py', 'test_stream_lifecycle.py', 'test_pipeline_message_callback.py', 'test_native_metadata.py', 'test_composition_architecture.py']:
        suite.addTests(unittest.defaultTestLoader.discover('tests', pattern=pattern))
    result = unittest.TextTestRunner(stream=log, verbosity=2).run(suite)
data = dict(status='PASS' if result.wasSuccessful() else 'FAIL', tests=result.testsRun, failures=len(result.failures), errors=len(result.errors), gpu_nodes=0, sdk_stop_call='PASS', live_inference=False)
(R/(mode+'-verify.json')).write_text(json.dumps(data, indent=2))
print(json.dumps(data))
sys.exit(not result.wasSuccessful())
