# -*- coding: utf-8 -*-
"""Trích vài khung hình từ video hiện trường Base (Đăng Long) bằng JS trong Chrome."""
import os, re, subprocess, time, json, base64, urllib.request

EXE = r"C:\Users\admin\.local\bin\browser-act.exe"
SES = "base1"
W = r"C:\Claw 2\QC\Base\Dang-Long-troc-son"
TMP = os.path.join(W, "_video")
os.makedirs(TMP, exist_ok=True)
urls = json.load(open(os.path.join(TMP, "video_urls.json"), encoding="utf-8"))
views = [u for u in urls if "/view/" in u]
print("video:", len(views))

def run(a, t=300):
    p = subprocess.run([EXE, "--session", SES] + a, capture_output=True, text=True,
                       encoding="utf-8", errors="replace", timeout=t)
    return ((p.stdout or "") + (p.stderr or "")).strip()

SHOT = """(async()=>{try{
 const v=document.querySelector('video'); if(!v) return 'NO-VIDEO';
 if(!v.paused) v.pause();
 const seek=t=>new Promise(r=>{const h=()=>{v.removeEventListener('seeked',h);r()};v.addEventListener('seeked',h);v.currentTime=t;setTimeout(r,2500)});
 await seek(%TIME%);
 await new Promise(r=>setTimeout(r,900));
 const W=Math.min(1000, v.videoWidth||1000), H=Math.round(W*(v.videoHeight||560)/(v.videoWidth||1000));
 const c=document.createElement('canvas'); c.width=W; c.height=H;
 c.getContext('2d').drawImage(v,0,0,W,H);
 return c.toDataURL('image/jpeg',0.72);
}catch(e){return 'ERR '+e.message}})()"""

saved = []
for vi, u in enumerate(views, 1):
    run(["navigate", u], 240); time.sleep(9)
    info = run(["eval", "(()=>{const v=document.querySelector('video');return v?JSON.stringify({w:v.videoWidth,h:v.videoHeight,d:isFinite(v.duration)?v.duration:0}):'NO-VIDEO';})()"], 120)
    print(f"\nvideo {vi}: {info[:120]}")
    m = re.search(r"\{.*\}", info, re.S)
    dur = json.loads(m.group(0)).get("d", 10) if m else 10
    times = [t for t in (1.0, 3.0, 5.0, 8.0, 12.0) if t < max(dur - 0.5, 2)]
    for t in times:
        out = run(["eval", SHOT.replace("%TIME%", str(t))], 300)
        mm = re.search(r"data:image/jpeg;base64,([A-Za-z0-9+/=]+)", out)
        if not mm:
            print(f"   t={t}s: {out[:110]}")
            continue
        b = base64.b64decode(mm.group(1))
        fname = f"video{vi}_t{t:04.1f}.jpg"
        open(os.path.join(TMP, fname), "wb").write(b)
        saved.append(fname)
        print(f"   t={t}s → {fname} [{len(b)//1024} KB]")
        time.sleep(1)
json.dump(saved, open(os.path.join(TMP, "frames.json"), "w", encoding="utf-8"), indent=1)
print("\nđã lưu", len(saved), "khung hình vào", TMP)
