# -*- coding: utf-8 -*-
"""In HTML → PDF bằng Chrome headless + verify bằng pymupdf."""
import os, subprocess, glob, sys

D = r"C:\Claw 2\QC\Base\Dang-Long-troc-son"
HTML = os.path.join(D, "Bao-cao-troc-son_Dang-Long_DL-16-19.html")
PDF = os.path.join(D, "Bao-cao-troc-son_Dang-Long_DL-16-19.pdf")

cands = [r"C:\Program Files\Google\Chrome\Application\chrome.exe",
         r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
         os.path.expandvars(r"%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe")]
chrome = next((c for c in cands if os.path.exists(c)), None)
print("chrome:", chrome)
if not chrome:
    sys.exit("không tìm thấy Chrome")

prof = os.path.join(D, "chrome_tmp")
os.makedirs(prof, exist_ok=True)
r = subprocess.run([chrome, "--headless=new", "--disable-gpu", "--no-sandbox",
                    f"--user-data-dir={prof}", f"--print-to-pdf={PDF}",
                    "--no-pdf-header-footer", "--virtual-time-budget=8000",
                    "file:///" + HTML.replace("\\", "/")],
                   capture_output=True, text=True, timeout=180)
print("exit:", r.returncode, "| stderr:", (r.stderr or "")[-200:])
print("PDF:", os.path.getsize(PDF) // 1024, "KB" if os.path.exists(PDF) else "KHÔNG TẠO ĐƯỢC")

# verify
import pymupdf
doc = pymupdf.open(PDF)
print(f"\n=== VERIFY: {doc.page_count} trang ===")
for i, page in enumerate(doc, 1):
    txt = page.get_text()
    print(f"  trang {i}: ảnh {len(page.get_images())} | ký tự {len(txt):>5} | bắt đầu: {txt.strip().splitlines()[0][:60] if txt.strip() else '(trống)'}")
# render trang 1 + trang có sơ đồ để kiểm bằng mắt
for i in (1, 3):
    if i <= doc.page_count:
        pix = doc[i - 1].get_pixmap(dpi=70)
        p = os.path.join(D, f"_check_trang{i}.png")
        pix.save(p)
        print("  ảnh kiểm tra:", p)
doc.close()
