# -*- coding: utf-8 -*-
"""Mở board Base → lấy HTML → liệt kê job cards theo từng cột (stage)."""
import os, re, subprocess, time, json, sys

EXE = r"C:\Users\admin\.local\bin\browser-act.exe"
SES = "base1"
BOARD = "https://workflow.base.vn/baseqtxulysucokhongphuhoptaikh-13544"
TMP = r"C:\Users\admin\AppData\Local\Temp\base_jobs"
os.makedirs(TMP, exist_ok=True)

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

out = run(["browser", "open", "direct_local_116683762948898908", BOARD], 300)
print("open:", out[:200])
time.sleep(10)
run(["wait", "stable"], 180)
html = run(["get", "html"], 300)
p = os.path.join(TMP, "board.html")
open(p, "w", encoding="utf-8").write(html)
print("html:", len(html), "ký tự →", p)

cards = re.findall(r'title="([^"]*?Id: (\d+) \| Công việc: (\d+)[^"]*)"[^>]*data-stage="(\d+)"', html)
if not cards:
    cards = re.findall(r'data-stage="(\d+)"[^>]*title="([^"]*?Id: (\d+) \| Công việc: (\d+)[^"]*)"', html)
    cards = [(t, i, c, s) for s, t, i, c in cards]
print("tổng card tìm được:", len(cards))

STAGES = {"95344": "Thông tin không phù hợp", "95246": "Kiểm tra & xử lý sự cố",
          "95248": "QC & KT kiểm tra nguyên nhân gốc rễ", "95250": "GD duyệt kết quả báo cáo",
          "95252": "Theo dõi tình trạng", "98799": "Theo dõi - nghiên cứu",
          "95244": "Hoàn thành", "95245": "Thất bại"}
by = {}
for title, jid, ncv, stage in cards:
    by.setdefault(stage, []).append({"title": title.strip(), "job": jid, "cv": int(ncv)})
for s, items in sorted(by.items(), key=lambda x: -len(x[1])):
    print(f"\n[{s}] {STAGES.get(s, '?')}: {len(items)} vụ")
json.dump(by, open(os.path.join(TMP, "board_cards.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

hoan = by.get("95244", [])
print(f"\n=== CỘT HOÀN THÀNH: {len(hoan)} vụ ===")
for i, x in enumerate(hoan, 1):
    print(f"  {i:>2}. {x['title'][:110]}  (job {x['job']}, {x['cv']} cv)")
