"""Single bounded isolated suite; no live APIs or model inference."""
import contextlib
import io
import json
from pathlib import Path
import sys

mode=sys.argv[1]
assert mode in ('dev','site')
root=Path('/work');source=root/'source' if mode=='dev' else root
if mode=='site':
    for name in ('fight_r5/notification.py','fall_config.py','fall_geometry.py','fall_scenario.py'):
        path=root/'app'/name;path.parent.mkdir(parents=True,exist_ok=True)
        raw=(Path('/opt/contextra/app')/name).read_bytes()
        if path.exists():assert path.read_bytes()==raw
        else:path.write_bytes(raw)
sys.path[:0]=[str(source),str(source/'tests'),'/work','/opt/contextra']
import pytest

class Report:
    def __init__(self):self.passed=[];self.failed=[];self.errors=[];self.collected=0
    def pytest_collection_finish(self,session):self.collected=len(session.items)
    def pytest_collectreport(self,report):
        if report.failed:self.errors.append(str(report.longrepr))
    def pytest_runtest_logreport(self,report):
        if report.failed:(self.failed if report.when=='call' else self.errors).append(report.nodeid)
        elif report.when=='call' and report.passed:self.passed.append(report.nodeid)

names=['test_fall_r2_config','test_fall_r2','test_fall_core','test_fall_boundaries','test_fall_skip_hold',
       'test_fall_integration','test_fight_r5','test_fight_notification','test_fight_notification_runtime',
       'test_event_cooldown','test_loitering_settings','test_output_settings','test_async_restart']
known=['test_fall_integration.py::SettingsTests::test_fire_combination_no_save',
       'test_fall_integration.py::SettingsTests::test_roi_empty_aliases_and_independent_confidence']
args=['-q','-p','no:cacheprovider','/work/test_migration.py',*[str(source/'tests'/(n+'.py')) for n in names]]
args += ['--deselect='+str(source/'tests'/name) for name in known]
r=Report();buffer=io.StringIO()
with contextlib.redirect_stdout(buffer),contextlib.redirect_stderr(buffer):
    code=pytest.main(args,plugins=[r])
(root/(mode+'-pytest.log')).write_text(buffer.getvalue())
value=dict(exit_code=int(code),collected=r.collected,passed=len(r.passed),failed=r.failed,errors=r.errors,
           known_prior_failures_not_revalidated=known,mode=mode)
(root/(mode+'-tests.json')).write_text(json.dumps(value,indent=2))
print(json.dumps(value))
raise SystemExit(code)
