#!/usr/bin/env python3
from pathlib import Path
import subprocess,json,hashlib,re
r=Path('/data/video-pipeline/GacMaiAudio/project/gacmai_20260717_104203');p=r/'assets/audio/narration_final.wav';cue=json.loads((r/'artifacts/audio_cue_manifest.json').read_text())
probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-show_streams','-show_format','-of','json',str(p)],text=True))
dec=subprocess.run(['ffmpeg','-v','error','-i',str(p),'-f','null','-'],capture_output=True)
cp=subprocess.run(['ffmpeg','-hide_banner','-nostats','-i',str(p),'-af','loudnorm=I=-16:TP=-1.5:LRA=11:print_format=json','-f','null','-'],capture_output=True,text=True)
matches=re.findall(r'\{\s*"input_i".*?\}',cp.stderr,re.S);loud=json.loads(matches[-1]) if matches else {}
st=next(x for x in probe['streams'] if x['codec_type']=='audio');errs=[]
if st.get('codec_name')!='pcm_s16le' or st.get('sample_rate')!='48000' or st.get('channels')!=1:errs.append('format')
if dec.returncode:errs.append('decode')
I=float(loud.get('input_i',999));TP=float(loud.get('input_tp',999))
if abs(I-(-16.0))>0.2:errs.append('loudness')
if TP>-1.4:errs.append('true_peak')
out={'status':'passed' if not errs else 'failed','sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'duration':float(probe['format']['duration']),'codec':st.get('codec_name'),'sample_rate':st.get('sample_rate'),'channels':st.get('channels'),'integrated_lufs':I,'true_peak_dbfs':TP,'full_decode':'passed' if dec.returncode==0 else 'failed','cue_manifest':cue,'errors':errs};(r/'artifacts/audio_master_independent_qc.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out));raise SystemExit(1 if errs else 0)
