# -*- coding: utf-8 -*-
"""Chụp khối TTH270 trên portal (mở rộng) để kiểm tra hiển thị + ảnh."""
import os, io, subprocess
CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
P = r"C:\Claw 2\Bao cao - Hanh chinh\BAOCAOTONGHOP\HTML\KPH_TongHop_0508\index.html"
TMP = os.path.join(os.environ["LOCALAPPDATA"], "Temp", "kph_tth270")
os.makedirs(TMP, exist_ok=True)
h = io.open(P, encoding="utf-8").read()
inject = """<script>window.addEventListener('load',function(){
  var b=document.getElementById('tienhung-tth270');
  var head=b.querySelector('.inc-head'); if(head) head.click();
  var img=b.querySelectorAll('img'); var out=[];
  b.scrollIntoView({block:'start'});
  setTimeout(function(){ window.__kq = JSON.stringify(Array.from(img).map(function(i){return i.naturalWidth+'x'+i.naturalHeight;})); }, 600);
});</script>"""
p2 = os.path.join(TMP, "kph_tth270.html")
io.open(p2, "w", encoding="utf-8").write(h.replace("</body>", inject + "</body>"))
url = "file:///" + p2.replace("\\", "/").replace(" ", "%20")
out = os.path.join(TMP, "khoi_tth270.png")
subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run",
                f"--screenshot={out}", "--window-size=1400,2000", "--virtual-time-budget=8000",
                f"--user-data-dir={os.path.join(TMP,'prof')}", url], capture_output=True, timeout=240)
print("ảnh:", out, os.path.getsize(out)//1024, "KB")
# kiểm ảnh có tải được không (dùng --dump-dom sau khi set data attr)
inject2 = inject.replace("window.__kq =", "document.body.setAttribute('data-img', ")
inject2 = inject2.replace("; }, 600);", "); }, 2000);")
p3 = os.path.join(TMP, "kph_tth270_check.html")
io.open(p3, "w", encoding="utf-8").write(h.replace("</body>", inject2 + "</body>"))
r = subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--no-first-run", "--virtual-time-budget=9000",
                    "--dump-dom", f"--user-data-dir={os.path.join(TMP,'prof2')}",
                    "file:///" + p3.replace("\\", "/").replace(" ", "%20")],
                   capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=240)
import re
m = re.search(r'data-img="([^"]*)"', r.stdout or "")
print("kích thước ảnh hiển thị (naturalWidth x naturalHeight):", m.group(1) if m else "KHÔNG đọc được")
