# -*- coding: utf-8 -*-
"""Tải markdown 9 job cột Hoàn thành (chạy nền, không đưa vào context)."""
import os, subprocess, time, json, re

EXE = r"C:\Users\admin\.local\bin\browser-act.exe"
SES = "base1"
TMP = r"C:\Users\admin\AppData\Local\Temp\base_jobs"
os.makedirs(TMP, exist_ok=True)

cards = json.load(open(os.path.join(TMP, "board_cards.json"), encoding="utf-8"))
hoan = cards["95244"]

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

for i, x in enumerate(hoan, 1):
    jid = x["job"]
    dst = os.path.join(TMP, f"job_{jid}.md")
    if os.path.exists(dst) and os.path.getsize(dst) > 5000:
        print(f"  [{i}/9] {jid}: đã có, bỏ qua"); continue
    run(["navigate", f"https://workflow.base.vn/job/{jid}"], 240)
    time.sleep(7)                      # SPA render
    run(["wait", "stable"], 150)
    md = run(["get", "markdown"], 300)
    open(dst, "w", encoding="utf-8").write(md)
    print(f"  [{i}/9] {jid}: {len(md)} ký tự → {os.path.basename(dst)}")
    time.sleep(1)
print("\nXong tải 9 job.")
