#!/usr/bin/env python3
import json, os, subprocess, time, urllib.request
from pathlib import Path
ROOT=Path('/data/video-pipeline/HaTramAudio/project/011-Hieu-Sach-Dong-Cua-Vao-Ngay-Chung-Toi-Ly-Hon')
RUN='run-20260720T040439Z-a596ad16'; JOB='9feff3dc0d1c47648cc1fcd5f356fe2c'
URL=f'http://192.168.1.104:8023/v1/huyenan-render-final/jobs/{JOB}'
OUT=ROOT/'work'/ 'final'/RUN/'terminal-response.json'
LEASE='/home/hermes/.hermes/skills/audio-production/ha-tram-audio/scripts/gate_lease.py'
last=None
while True:
    with urllib.request.urlopen(URL,timeout=30) as r:data=json.load(r)
    marker=(data.get('status'),json.dumps(data.get('verification'),sort_keys=True,ensure_ascii=False))
    if marker!=last: print(data.get('status'),data.get('verification'),flush=True);last=marker
    subprocess.check_call(['python3',LEASE,'heartbeat','--project-root',str(ROOT),'--gate','final_render','--run-id',RUN,'--ttl-seconds','7200'],stdout=subprocess.DEVNULL)
    if data.get('status') in {'completed','failed','cancelled'}:
        tmp=OUT.with_name('.'+OUT.name+'.tmp')
        with tmp.open('w',encoding='utf-8') as f:json.dump(data,f,ensure_ascii=False,indent=2);f.write('\n');f.flush();os.fsync(f.fileno())
        os.replace(tmp,OUT)
        if data.get('status')!='completed' or data.get('verification',{}).get('verified') is not True:raise SystemExit(1)
        break
    time.sleep(3)
