import contextlib,glob,hashlib,json,os,unittest
from pathlib import Path
R=Path('/evidence');mode=os.environ['VERIFY_MODE'];root=Path('/source' if mode=='source' else '/opt/contextra')
assert Path.cwd()==root and not glob.glob('/dev/nvidia*')
expected=json.loads((R/'expected-source.json').read_text())
with (R/(mode+'-verify.log')).open('x') as log,contextlib.redirect_stdout(log),contextlib.redirect_stderr(log):
    import app.api.streams as routes
    import app.stream_manager as manager
    imports={}
    for mod,rel in [(routes,'app/api/streams.py'),(manager,'app/stream_manager.py')]:
        path=Path(mod.__file__).resolve();assert path==root/rel
        sha=hashlib.sha256(path.read_bytes()).hexdigest();assert sha==expected[rel]
        imports[rel]=dict(path=str(path),sha256=sha)
    suite=unittest.defaultTestLoader.loadTestsFromName('test_stream_registration_identity.RegistrationIdentityTests')
    result=unittest.TextTestRunner(stream=log,verbosity=2).run(suite)
    schema=routes.StreamSpec.model_json_schema();assert all(k in schema['properties'] for k in ('server_id','source_id','frame_time_anchor'))
    summary=dict(tests=result.testsRun,errors=len(result.errors),failures=len(result.failures),imports=imports,gpu_devices=0,
                 identity_schema={k:schema['properties'][k] for k in ('server_id','source_id')})
(R/(mode+'-verify.json')).write_text(json.dumps(summary,indent=2));print(json.dumps(summary));assert result.wasSuccessful()
