import json,os,pathlib,subprocess,sys
from artifact_install import ArtifactInstaller
from trace_install import command,load,sha

class DisplayInstaller(ArtifactInstaller):
    def test(self):
        self.guard()
        code="""import sys,json
sys.path.insert(0,'/work/tests')
import app.fight_r5.runtime as r,pytest
assert r.__file__.startswith('/opt/contextra/')
result=pytest.main(['-p','no:cacheprovider','-q','/work/tests/test_fight_display_hold.py','/work/tests/test_fight_r5.py','/work/tests/test_fight_notification_runtime.py','/work/tests/test_fight_notification.py'])
print('DISPLAY_TEST_EXIT',result);raise SystemExit(result)
"""
        code=code.replace('/work/tests','/opt/contextra/tests')
        p=subprocess.run(['docker','run','--rm','--user','0:0','--pull','never','--runtime','runc','--network','none','--read-only','--cpus','2','--memory','8g','--cap-drop','ALL','--security-opt','no-new-privileges','--tmpfs','/tmp:rw,size=128m','-e','NVIDIA_VISIBLE_DEVICES=void','-e','PYTHONDONTWRITEBYTECODE=1','--mount','type=bind,src='+str(self.root/'tests')+',dst=/opt/contextra/tests,readonly','--entrypoint','python3',load(self.root/'built.json')['image'],'-B','-c',code],capture_output=True,timeout=180)
        out=p.stdout+p.stderr
        self.fp.atomic(self.root/'tests-attempt.log',out)
        if p.returncode:raise RuntimeError(out.decode()[-2500:])
        self.fp.atomic(self.root/'tests.log',out);self.save('display-tests',{'passed':True})
        print(out.decode())
    def activate(self):
        assert load(self.root/'display-tests.json')['passed']
        _,rows=self.guard()
        row=rows['analytics'];env=dict(x.split('=',1) for x in row['Config']['Env'] if '=' in x)
        target=env['CONTEXTRA_ARTIFACT_ROOT']
        mounts=[m for m in row['Mounts'] if m['Destination']==target and m['Type']=='bind']
        assert len(mounts)==1
        path=pathlib.Path(mounts[0]['Source'])/'.fight-display-policy.json'
        assert not path.exists() and not path.is_symlink(),'Policy already exists; review first'
        if any(not n.startswith('contextra-ai2-') for n in command(['docker','ps','--format','{{.Names}}']).decode().split()):raise ValueError('OTHER_TRIAL_ACTIVE')
        for name,h in self.m['before'].items():
            actual=self.python(row['Id'],'import hashlib;print(hashlib.sha256(open('+repr('/opt/contextra/'+name)+',"rb").read()).hexdigest())').decode().strip()
            assert actual==h,'SOURCE_CAS'
        self.save('policy-backup',dict(path=str(path),existed=False,container_path=target+'/.fight-display-policy.json'))
        self.fp.atomic(path,dict(version=1,hold_seconds=3.0));path.chmod(0o644)
        self.save('indexes',dict(schema_change=False,index_change=False,reason='No DB changes required'))
        super().activate()
    def verify(self):
        super().verify()
        row=self.rows()['analytics'];path=load(self.root/'policy-backup.json')['container_path']
        value=json.loads(self.python(row['Id'],'import json;from app.fight_r5.display_policy import read;print(json.dumps(read('+repr(path)+')))'))
        assert value['hold_seconds']==3
        self.save('display-verified',dict(policy=value,source_verified=True,browser_acceptance=False))

if __name__=='__main__':
    root,action=sys.argv[1:]
    assert action in ('prepare','build','test','activate','verify')
    getattr(DisplayInstaller(root,'icerti-ai2'),action)()
