import subprocess
import json
import sys
from pathlib import Path

files = [
    "04_Assets/videos/prologue_shot01_10s_v1.mp4",
    "04_Assets/videos/prologue_shot02_10s_v1.mp4",
    "04_Assets/videos/prologue_shot03_10s_v1.mp4",
    "04_Assets/videos/prologue_shot04_10s_v1.mp4",
    "04_Assets/archive/prologue_pre_fix/prologue_shot_01_lang_que_198x_10s.mp4",
    "04_Assets/archive/prologue_pre_fix/prologue_shot_02_ngam_kieu_10s.mp4",
    "04_Assets/archive/prologue_pre_fix/prologue_shot_03_xuyen_khong_10s.mp4",
    "04_Assets/archive/prologue_pre_fix/prologue_shot_04_gia_tinh_trieu_minh_10s.mp4",
    "04_Assets/archive/prologue_pre_fix/prologue_shot04_corrected.mp4",
    "06_Exports/prologue_master_40s.mp4"
]

for f in files:
    p = Path(f)
    if not p.exists():
        continue
    cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-show_format", str(p)]
    res = subprocess.run(cmd, capture_output=True, text=True)
    try:
        d = json.loads(res.stdout)
        dur = d.get("format", {}).get("duration", "N/A")
        v_s = [s for s in d.get("streams", []) if s.get("codec_type") == "video"]
        a_s = [s for s in d.get("streams", []) if s.get("codec_type") == "audio"]
        w = v_s[0].get("width") if v_s else None
        h = v_s[0].get("height") if v_s else None
        fps = v_s[0].get("r_frame_rate") if v_s else None
        v_codec = v_s[0].get("codec_name") if v_s else None
        v_str = f"{w}x{h} @ {fps} {v_codec}" if v_s else "No V"
        a_codec = a_s[0].get("codec_name") if a_s else None
        sr = a_s[0].get("sample_rate") if a_s else None
        ch = a_s[0].get("channels") if a_s else None
        a_str = f"{a_codec} {sr}Hz {ch}ch" if a_s else "No A"
        print(f"{p.name:45s} | dur={float(dur):.2f}s | {v_str:25s} | {a_str}")
    except Exception as e:
        print(f"{p.name}: error {e}")

print("\n--- AUDIO FILES IN prologue_inspect ---")
audio_dir = Path("04_Assets/audio/prologue_inspect")
sys.path.append("05_Production_Pipeline")
from audio_continuity_engine import AudioContinuityEngine
ace = AudioContinuityEngine()

if audio_dir.exists():
    for f in sorted(audio_dir.iterdir()):
        if f.suffix in [".wav", ".mp3", ".m4a"]:
            try:
                info = ace.inspect_shot_audio(str(f))
                loud = ace.measure_loudness(str(f))
                max_v = info.get("max_volume_db", -99.0)
                mean_v = info.get("mean_volume_db", -99.0)
                inp_i = loud.get("input_i", "N/A")
                inp_tp = loud.get("input_tp", "N/A")
                inp_lra = loud.get("input_lra", "N/A")
                print(f"{f.name:45s} | dur={info.get('duration', 0):.2f}s | I={inp_i:>6} LUFS, TP={inp_tp:>5} dBTP | max={max_v:>5.1f}dB, mean={mean_v:>5.1f}dB")
            except Exception as e:
                print(f"{f.name}: {e}")
