#!/usr/bin/env python3
"""
kiem_tra_geostory.py — Bộ kiểm tra tự động chuẩn Video Bản Đồ + Chibi (Mẫu Louisiana)
Dùng cho Bot DOT (ChatGPT) kiểm tra TRƯỚC & SAU khi render bằng GeoStory_Studio_7.0_LiveDrive_AI.html.

Cách chạy:
  python kiem_tra_geostory.py video.mp4 --script kich_ban.json
  python kiem_tra_geostory.py video.mp4 --script kich_ban.json --short   # cho clip test 20-55s
"""
import argparse, json, os, re, subprocess, sys

META_OPS = {
    "glowRiver", "thoughtBubble", "priceTag", "stickConflict", "rewind",
    "mapProp", "portraitCameo", "territoryMorph", "iconBurst", "counter",
    "stamp", "multiArc", "splitCompare"
}

def run_cmd(cmd):
    return subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")

def check_script(script_path, short_mode=False):
    rows = []
    def add(name, val, need, ok):
        rows.append((ok, "Kịch bản", name, str(val), need))

    with open(script_path, "r", encoding="utf-8") as f:
        steps = json.load(f)
    if not isinstance(steps, list) or not steps:
        add("Cấu trúc JSON mảng bước", "không hợp lệ", "mảng JSON >= 10 lệnh", False)
        return rows

    types = {s.get("do") for s in steps if isinstance(s, dict) and s.get("do")}
    setup = next((s for s in steps if isinstance(s, dict) and s.get("do") == "setup"), {})
    frame = setup.get("frame", "9:16")
    sub_style = setup.get("subStyle", "louisiana")
    fly_cnt = sum(1 for s in steps if isinstance(s, dict) and s.get("do") in ("flyTo", "camera"))
    terr_cnt = sum(1 for s in steps if isinstance(s, dict) and s.get("do") in ("territory", "select", "territoryMorph"))
    actor_cnt = sum(1 for s in steps if isinstance(s, dict) and s.get("do") in ("mapActor", "updateActor"))
    diorama_cnt = sum(1 for s in steps if isinstance(s, dict) and s.get("do") in ("diorama25d", "skit", "puppet"))
    meta_cnt = sum(1 for s in steps if isinstance(s, dict) and s.get("do") in META_OPS)
    say_cnt = sum(1 for s in steps if isinstance(s, dict) and s.get("do") in ("say", "subtitle"))
    max_wait = max([float(s.get("seconds", 0)) for s in steps if isinstance(s, dict) and s.get("do") == "wait"] or [0.0])
    has_morph_or_river = ("territoryMorph" in types) or ("glowRiver" in types)
    has_audio = "audio" in types

    min_fly = 2 if short_mode else 4
    min_meta = 3 if short_mode else 5
    min_say = 3 if short_mode else 6
    min_types = 6 if short_mode else 8

    add("Khung hình dọc 9:16", frame, "9:16", frame == "9:16")
    add("Kiểu phụ đề 2-4 từ Louisiana", sub_style, "louisiana", sub_style == "louisiana")
    add("Bản đồ bay liên tục (flyTo/camera)", f"{fly_cnt} cú bay", f">= {min_fly} cú bay mượt", fly_cnt >= min_fly)
    add("Tô lãnh thổ / biên giới vector", f"{terr_cnt} lệnh", ">= 2 vùng", terr_cnt >= 2)
    add("Nhân vật Chibi/Cutout trên bản đồ", f"{actor_cnt} lệnh", ">= 2 nhân vật/lượt diễn", actor_cnt >= 2)
    add("Ẩn dụ thị giác (Visual Metaphor)", f"{meta_cnt} chiêu", f">= {min_meta} chiêu", meta_cnt >= min_meta)
    add("Morph lãnh thổ hoặc Sông phát sáng", "có" if has_morph_or_river else "thiếu", "territoryMorph hoặc glowRiver", has_morph_or_river)
    add("Cảnh lặn xuống thực địa 2.5D", f"{diorama_cnt} cảnh", ">= 1 cảnh diorama25d", diorama_cnt >= 1)
    add("Độ đa dạng chiêu dựng", f"{len(types)} loại lệnh", f">= {min_types} loại", len(types) >= min_types)
    add("Không đứng im lâu (max wait)", f"{max_wait:.1f}s", "<= 3.5s", max_wait <= 3.5)
    add("Nhịp phụ đề đồng bộ", f"{say_cnt} câu", f">= {min_say} câu", say_cnt >= min_say)
    add("Cấu hình âm thanh -14.5 LUFS", "bật" if has_audio else "thiếu", "có lệnh audio", has_audio)
    return rows

def check_video(video_path, short_mode=False):
    rows = []
    def add(name, val, need, ok):
        rows.append((ok, "Video/Audio", name, str(val), need))

    if not os.path.exists(video_path):
        add("Tệp MP4 tồn tại", "không thấy", video_path, False)
        return rows

    p = run_cmd(["ffprobe", "-v", "error", "-show_format", "-show_streams", "-of", "json", video_path])
    if p.returncode != 0:
        add("Đọc thông tin ffprobe", "lỗi", "MP4 hợp lệ", False)
        return rows
    info = json.loads(p.stdout)
    dur = float(info.get("format", {}).get("duration", 0))
    vs = next((s for s in info.get("streams", []) if s.get("codec_type") == "video"), None)
    as_ = next((s for s in info.get("streams", []) if s.get("codec_type") == "audio"), None)

    w = int(vs.get("width", 0)) if vs else 0
    h = int(vs.get("height", 0)) if vs else 0
    fps_s = vs.get("r_frame_rate", "0/1") if vs else "0/1"
    num, den = (fps_s.split("/") + ["1"])[:2]
    fps = float(num) / max(1.0, float(den))

    add("Độ phân giải 9:16 chuẩn", f"{w}x{h}", "1080x1920 hoặc 720x1280", (w, h) in ((1080, 1920), (720, 1280)))
    add("Tốc độ khung hình", f"{fps:.1f} fps", "30 fps", 29.0 <= fps <= 31.0)
    min_d, max_d = (18.0, 115.0) if short_mode else (50.0, 115.0)
    add("Thời lượng video", f"{dur:.1f}s", f"{min_d:.0f}-{max_d:.0f}s", min_d <= dur <= max_d)
    add("Có kênh âm thanh AAC/Stereo", as_.get("codec_name") if as_ else "không có", "aac", bool(as_))

    # Scene cut flicker check (< 0.6s between hard cuts)
    sc = run_cmd(["ffmpeg", "-i", video_path, "-vf", "select=gt(scene\\,0.35),showinfo", "-f", "null", "-"])
    cuts = [float(m) for m in re.findall(r"pts_time:([0-9.]+)", sc.stderr)]
    flicker = sum(1 for i in range(1, len(cuts)) if cuts[i] - cuts[i - 1] < 0.6)
    add("Cắt giật (< 0.6s)", flicker, "0", flicker == 0)

    # Audio loudness (EBU R128) & longest silence
    if as_:
        au = run_cmd(["ffmpeg", "-i", video_path, "-af", "ebur128=framelog=quiet,silencedetect=n=-38dB:d=0.35", "-f", "null", "-"])
        lufs_m = re.search(r"I:\s*(-?[0-9.]+)\s*LUFS", au.stderr)
        lra_m = re.search(r"LRA:\s*([0-9.]+)\s*LU", au.stderr)
        sil_durs = [float(x) for x in re.findall(r"silence_duration:\s*([0-9.]+)", au.stderr)]
        max_sil = max(sil_durs) if sil_durs else 0.0
        lufs = float(lufs_m.group(1)) if lufs_m else -99.0
        lra = float(lra_m.group(1)) if lra_m else 99.0
        add("Độ to âm thanh (LUFS)", f"{lufs:.1f} LUFS", "-16.5 đến -12.5 LUFS (mục tiêu -14.5)", -16.5 <= lufs <= -12.5)
        add("Độ nén âm thanh đều (LRA)", f"{lra:.1f} LU", "<= 6.0 LU", lra <= 6.0)
        add("Khoảng im lặng dài nhất", f"{max_sil:.2f}s", "<= 0.70s", max_sil <= 0.70)

    return rows

def main():
    ap = argparse.ArgumentParser(description="Kiểm tra video GeoStory 7.0 chuẩn mẫu Louisiana")
    ap.add_argument("video", nargs="?", help="Đường dẫn file .mp4")
    ap.add_argument("--script", "-s", help="Đường dẫn file kịch bản JSON GeoStory 7.0")
    ap.add_argument("--short", action="store_true", help="Chế độ kiểm tra clip ngắn (18-55s)")
    args = ap.parse_args()

    if not args.video and not args.script:
        ap.print_help()
        sys.exit(2)

    all_rows = []
    if args.script:
        all_rows.extend(check_script(args.script, args.short))
    if args.video:
        all_rows.extend(check_video(args.video, args.short))

    passed = sum(1 for r in all_rows if r[0])
    total = len(all_rows)
    print(f"=== KẾT QUẢ KIỂM TRA GEOSTORY 7.0: {passed}/{total} ĐẠT ===")
    for ok, grp, name, val, need in all_rows:
        st = "ĐẠT      " if ok else "KHÔNG ĐẠT"
        print(f"{st} | {grp:<11} | {name:<36} | {val:<18} | cần: {need}")
    sys.exit(0 if passed == total else 1)

if __name__ == "__main__":
    main()
