#!/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='5053ebcaa7e64de68eeb8b61625fe6bc'
URL=f'http://192.168.1.104:8024/v1/huyenan-transcode-upload/jobs/{JOB}';OUT=ROOT/'work'/'transcode'/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','transcode','--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)
        v=data.get('verification',{})
        if data.get('status')!='completed' or v.get('verified') is not True or v.get('under_one_gb') is not True:raise SystemExit(1)
        break
    time.sleep(5)
