#!/usr/bin/env python3
"""
video-qc: 短视频成片与分镜双层硬质检工具 (技术参数 + 响度/静音 + Whisper 台词对齐 + 人脸检测 + 多模态视觉审查)
用法：
  video-qc <video.mp4> [--expected-text "台词文本"] [--vision-prompt "检查左下角关注箭头与字幕是否压线"]
"""
import argparse, base64, json, os, re, subprocess, sys, tempfile, urllib.request

def run(cmd):
    return subprocess.run(cmd, capture_output=True, text=True)

def inspect_streams(path):
    r = run(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", path])
    return json.loads(r.stdout or "{}")

def check_audio_loudness_and_silence(path):
    r = run(["ffmpeg", "-hide_banner", "-nostats", "-i", path, "-af", "silencedetect=noise=-38dB:d=0.4,ebur128=peak=true", "-f", "null", "-"])
    txt = (r.stdout or "") + "\n" + (r.stderr or "")
    i_matches = re.findall(r"I:\s*(-?\d+(?:\.\d+)?)\s*LUFS", txt)
    lufs = float(i_matches[-1]) if i_matches else None
    silences = re.findall(r"silence_end:\s*([0-9.]+)\s*\|\s*silence_duration:\s*([0-9.]+)", txt)
    return {"integrated_lufs": lufs, "silences": [{"end": float(e), "dur": float(d)} for e, d in silences]}

def check_whisper(path):
    try:
        from faster_whisper import WhisperModel
        cache_dir = os.environ.get("WHISPER_MODEL_CACHE", "/opt/models/whisper")
        if not os.path.exists(cache_dir):
            cache_dir = "/root/.openclaw/models/whisper"
        model = WhisperModel("small", device="cpu", compute_type="int8", download_root=cache_dir)
        segs, _ = model.transcribe(path, language="zh", vad_filter=True)
        items = [{"start": round(s.start, 2), "end": round(s.end, 2), "text": s.text.strip()} for s in segs]
        return {"text": "".join(x["text"] for x in items), "segments": items}
    except Exception as e:
        return {"error": str(e)}

def check_faces_and_brightness(path, dur):
    import cv2, numpy as np
    pts = [max(0.2, min(dur - 0.2, dur * r)) for r in (0.15, 0.5, 0.85)]
    brights = []
    faces_found = 0
    cascade = None
    if hasattr(cv2, "CascadeClassifier") and hasattr(cv2, "data"):
        xml = os.path.join(cv2.data.haarcascades, "haarcascade_frontalface_default.xml")
        if os.path.exists(xml):
            cascade = cv2.CascadeClassifier(xml)
    cap = cv2.VideoCapture(path)
    for t in pts:
        cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0)
        ok, frame = cap.read()
        if not ok or frame is None:
            continue
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        brights.append(round(float(np.mean(gray)), 1))
        if cascade is not None:
            det = cascade.detectMultiScale(gray, 1.15, 4)
            faces_found += len(det)
    cap.release()
    return {"mean_brightness": brights, "min_brightness": min(brights) if brights else 0, "faces_detected_total": faces_found}

def check_vision_api(path, dur, prompt):
    api_url = (os.environ.get("APIYI_BASE_URL") or "https://api.apiyi.com/v1").rstrip("/") + "/chat/completions"
    api_key = os.environ.get("APIYI_API_KEY") or ""
    if not api_key:
        return {"skipped": "No APIYI_API_KEY configured"}
    with tempfile.TemporaryDirectory() as tmp:
        grid = os.path.join(tmp, "grid.jpg")
        fps_expr = f"fps=4/{max(1.0, dur)}"
        run(["ffmpeg", "-y", "-v", "error", "-i", path, "-vf", f"{fps_expr},scale=360:-2,tile=2x2", "-frames:v", "1", grid])
        if not os.path.exists(grid):
            return {"error": "Failed to extract contact sheet"}
        b64 = base64.b64encode(open(grid, "rb").read()).decode("ascii")
    payload = {
        "model": "qwen3-vl-plus",
        "messages": [{
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}
            ]
        }],
        "max_tokens": 600
    }
    req = urllib.request.Request(
        api_url,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
    )
    try:
        with urllib.request.urlopen(req, timeout=45) as resp:
            res = json.loads(resp.read().decode("utf-8", errors="replace"))
            return {"model": "qwen3-vl-plus", "review": res["choices"][0]["message"]["content"]}
    except Exception as e:
        return {"error": str(e)}

def main():
    p = argparse.ArgumentParser()
    p.add_argument("video")
    p.add_argument("--expected-text", default="")
    p.add_argument("--skip-whisper", action="store_true")
    p.add_argument("--vision-prompt", default="")
    args = p.parse_args()

    info = inspect_streams(args.video)
    streams = info.get("streams") or []
    vstream = next((s for s in streams if s.get("codec_type") == "video"), {})
    astream = next((s for s in streams if s.get("codec_type") == "audio"), {})
    dur = float((info.get("format") or {}).get("duration") or vstream.get("duration") or 0)
    rot = 0
    for sd in vstream.get("side_data_list") or []:
        if "rotation" in sd:
            rot = int(float(sd["rotation"]))

    report = {
        "file": args.video,
        "duration_s": round(dur, 3),
        "video": {
            "width": vstream.get("width"),
            "height": vstream.get("height"),
            "rotation": rot,
            "sar": vstream.get("sample_aspect_ratio", "1:1"),
            "fps": vstream.get("r_frame_rate"),
            "pix_fmt": vstream.get("pix_fmt")
        },
        "audio": {
            "codec": astream.get("codec_name"),
            "channels": astream.get("channels"),
            "sample_rate": astream.get("sample_rate")
        },
        "acoustics": check_audio_loudness_and_silence(args.video) if astream else {"error": "NO_AUDIO_STREAM"},
        "visual_probe": check_faces_and_brightness(args.video, dur) if dur > 0 else {}
    }
    if not args.skip_whisper and astream:
        report["whisper_asr"] = check_whisper(args.video)
    if args.vision_prompt and dur > 0:
        report["vision_qc"] = check_vision_api(args.video, dur, args.vision_prompt)

    warnings = []
    if astream and astream.get("channels", 0) < 2:
        warnings.append("AUDIO_MONO: 音轨为单声道(1ch)，合成时请加 aformat=channel_layouts=stereo")
    lufs = (report["acoustics"] or {}).get("integrated_lufs")
    if lufs is not None and (lufs < -24 or lufs > -10):
        warnings.append(f"LOUDNESS_OUT_OF_RANGE: 综合响度 {lufs} LUFS 偏离标准区间 [-18, -13] LUFS")
    if (report["visual_probe"] or {}).get("min_brightness", 99) < 12:
        warnings.append("BLACK_FRAME_RISK: 采样帧最低平均亮度 < 12，疑似存在黑场")
    report["warnings"] = warnings
    report["passed"] = (len(warnings) == 0 and bool(vstream) and bool(astream))
    print(json.dumps(report, ensure_ascii=False, indent=2))

if __name__ == "__main__":
    main()
