#!/usr/bin/env python3
from __future__ import annotations
import argparse,json,time,urllib.request
from pathlib import Path
from project_runtime import atomic_write_json,require_project_root,valid_asr,valid_wav,save_stage
URL='http://192.168.1.103:8001/transcribe-and-save'
def main():
 ap=argparse.ArgumentParser();ap.add_argument('project');ap.add_argument('--ids',nargs='*',type=int);a=ap.parse_args();p=require_project_root(Path(a.project));m=json.loads((p/'narration/narration.json').read_text());items=m['items'];wanted=set(a.ids or [x['id'] for x in items]);results=[]
 for x in items:
  if x['id'] not in wanted:continue
  wav=Path(x['audio_path']);wav=wav if wav.is_absolute() else p/wav;out=Path(x['asr_path']);out=out if out.is_absolute() else p/out
  if not valid_wav(wav):results.append({'id':x['id'],'status':'blocked_invalid_wav'});continue
  if valid_asr(out):results.append({'id':x['id'],'status':'existing'});continue
  out.parent.mkdir(parents=True,exist_ok=True);ok=False;err=''
  for attempt in range(4):
   req=urllib.request.Request(URL,data=json.dumps({'input_path':str(wav),'output_path':str(out),'language':'vi','task':'transcribe','word_timestamps':True}).encode(),headers={'Content-Type':'application/json'},method='POST')
   try:
    with urllib.request.urlopen(req,timeout=600) as r:body=r.read()
    if not out.exists() and body:
     try:atomic_write_json(out,json.loads(body))
     except:pass
    if valid_asr(out):ok=True;break
    err='invalid_asr'
   except Exception as e:err=type(e).__name__
   time.sleep(2**attempt)
  results.append({'id':x['id'],'status':'ok' if ok else 'fail','error':err if not ok else None})
 valid=[x['id'] for x in items if valid_asr((Path(x['asr_path']) if Path(x['asr_path']).is_absolute() else p/x['asr_path']))];report={'status':'PASS' if len(valid)==len(items) else 'FAIL','expected':len(items),'valid':valid,'results':results};atomic_write_json(p/'logs/asr_gate.json',report)
 if report['status']=='PASS':save_stage(p,'ASR','PASS',{'count':len(valid)})
 print(json.dumps(report));raise SystemExit(0 if report['status']=='PASS' else 1)
if __name__=='__main__':main()
