import json
from pathlib import Path
import subprocess
import sys
import time

out=Path(__file__).parent
phase,seconds=sys.argv[1],int(sys.argv[2])
dest=out/(phase+'.json')
if dest.exists():raise SystemExit('Preserve existing observation')
repo=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
code=(repo/'tools/icerti_offline/event_pin_probe.py').read_text()
ledger=(repo/'tools/icerti_offline/artifact_lifecycle_probe.py').read_text().split("if __name__=='__main__':")[0]
ssh=['ssh','-T','-p','1022','-i','/root/.ssh/ltb1021_contextra_icerti2_si_ed25519','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o','UserKnownHostsFile=/root/.ssh/contextra_icerti2_known_hosts','si@58.233.207.31']
start=time.time();begin=time.monotonic();rows=[]
for n in range(seconds//5+1):
    time.sleep(max(0,begin+n*5-time.monotonic()))
    p=subprocess.run(ssh+['docker exec -i contextra-ai2-analytics-1 python3 -B -'],input=code,text=True,capture_output=True,timeout=15)
    if p.returncode:raise SystemExit(p.stderr[-500:])
    rows.append(json.loads(p.stdout))
    dest.write_text(json.dumps(dict(phase=phase,start=start,elapsed=time.monotonic()-begin,samples=rows)))
safe=ledger+'\nr=sample('+repr(start)+')\n'
safe+="for v in r['claims']:v.pop('claim_token',None)\nfor v in r['channels']:\n v.pop('render_token',None)\n v.pop('send_token',None)\nprint(json.dumps(r))\n"
p=subprocess.run(ssh+['docker exec -i contextra-ai2-analytics-1 python3 -B -'],input=safe,text=True,capture_output=True,timeout=15)
if p.returncode:raise SystemExit(p.stderr[-500:])
(out/(phase+'-ledger.json')).write_text(json.dumps(json.loads(p.stdout)))
print(json.dumps(dict(phase=phase,samples=len(rows),elapsed=time.monotonic()-begin)))
