"""One private-runner poll. Supply the engagement credential through a protected file."""
import argparse,json,os,subprocess,sys
from pathlib import Path
import requests
def main():
    parser=argparse.ArgumentParser()
    for flag in ('portal','target','key-file','runner'):
        parser.add_argument('--'+flag,required=True)
    parser.add_argument('--assertions')
    a=parser.parse_args()
    if not a.portal.startswith('https://'):raise ValueError('Portal requires HTTPS')
    key=Path(a.key_file).read_text().strip()
    base=a.portal.rstrip('/')+'/api/v1/engagement/monitoring'
    auth={'Authorization':'Bearer '+key}
    r=requests.post(base+'/claim',headers=auth,timeout=20,allow_redirects=False)
    if r.status_code==204:return
    r.raise_for_status();e=r.json();lock=e['locked_set']
    cmd=[sys.executable,a.runner,'--portal',a.portal,'--target',a.target,'--version',e['target_version'],'--reference',e['reference'],'--set-hash',lock['hash'],'--set-version',str(lock['version'])]
    if a.assertions:cmd+=['--assertions',a.assertions]
    ret=subprocess.run(cmd,input=key+'\n',text=True,capture_output=True,timeout=3600)
    if ret.returncode:
        # A committed submission can outlive a response timeout. The server checks its state.
        requests.post(base+'/failure',headers=auth,json={'reference':e['reference']},timeout=15,allow_redirects=False).raise_for_status()
        raise RuntimeError('Private runner failed; see monitoring event.')
if __name__=='__main__':main()

