# -*- coding: utf-8 -*-
"""Tải markdown TẤT CẢ job còn lại của board Base (mọi cột)."""
import os, subprocess, time, json

EXE = r"C:\Users\admin\.local\bin\browser-act.exe"
SES = "base1"
TMP = r"C:\Users\admin\AppData\Local\Temp\base_jobs"
cards = json.load(open(os.path.join(TMP, "board_cards.json"), encoding="utf-8"))
allj = []
for st, items in cards.items():
    for x in items:
        allj.append((st, x["job"], x["title"]))
print("tổng job trên board:", len(allj))

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()

done = 0
for st, jid, title in allj:
    dst = os.path.join(TMP, f"job_{jid}.md")
    if os.path.exists(dst) and os.path.getsize(dst) > 5000:
        continue
    run(["navigate", f"https://workflow.base.vn/job/{jid}"], 240)
    time.sleep(7)
    run(["wait", "stable"], 150)
    md = run(["get", "markdown"], 300)
    open(dst, "w", encoding="utf-8").write(md)
    done += 1
    print(f"  [{done}] stage {st} job {jid}: {len(md)} ký tự | {title[:60]}")
print("\nXong. Đã tải thêm", done, "job. Tổng file:",
      len([f for f in os.listdir(TMP) if f.startswith('job_')]))
