# -*- coding: utf-8 -*-
"""Lấy link video hiện trường từ job Base Đăng Long → tải → cắt khung hình."""
import os, re, subprocess, time, json, 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)

def run(a, t=240):
    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()

run(["navigate", "https://workflow.base.vn/job/3541940"], 240)
time.sleep(9)
run(["wait", "stable"], 150)
html = run(["get", "html"], 300)
open(os.path.join(TMP, "job.html"), "w", encoding="utf-8").write(html)
print("html:", len(html))

cands = set()
for m in re.finditer(r'https://[^"\'\\\s<>]+?\.mp4[^"\'\\\s<>]*', html):
    cands.add(m.group(0))
for m in re.finditer(r'"(https://[^"]*(?:download|file|attach)[^"]*)"', html):
    if "3541940" in m.group(1) or "workflow" in m.group(1):
        cands.add(m.group(1))
print("ứng viên URL:", len(cands))
for u in list(cands)[:12]:
    print("   ", u[:150])
json.dump(sorted(cands), open(os.path.join(TMP, "video_urls.json"), "w", encoding="utf-8"), indent=1)
