import hashlib
import importlib
import json
from pathlib import Path
import sys
import unittest


def main():
    root='/opt/contextra/' if 'image' in sys.argv[1] else '/source/'
    for name in ('app.stream_manager','app.channel_process','app.process_metadata','app.channel_child'):
        file=Path(importlib.import_module(name).__file__)
        assert str(file).startswith(root)
        print(name,str(file),hashlib.sha256(file.read_bytes()).hexdigest(),flush=True)
    assert 'pyservicemaker' not in sys.modules, 'Parent imported SDK before spawn'
    sys.path.insert(0,'/tests')
    suite=unittest.TestSuite()
    for pattern in ('test_channel_process.py','test_process_metadata.py','test_stream_lifecycle.py',
                    'test_det_result_path.py','test_stream_registration_identity.py','test_analysis_metrics.py'):
        suite.addTests(unittest.defaultTestLoader.discover('/tests',pattern=pattern))
    result=unittest.TextTestRunner(verbosity=2).run(suite)
    summary=dict(success=result.wasSuccessful(),tests=result.testsRun,errors=len(result.errors),failures=len(result.failures),skipped=len(result.skipped))
    Path('/evidence',sys.argv[1]+'.json').write_text(json.dumps(summary))
    print(json.dumps(summary),flush=True)
    return 0 if result.wasSuccessful() else 1


if __name__=='__main__':
    raise SystemExit(main())
