# -*- coding: utf-8 -*-
"""Tách riêng khối TTH270 + CSS portal → chụp để kiểm tra ảnh/nội dung hiển thị."""
import io, os, re, subprocess
from bs4 import BeautifulSoup
CL2 = r"C:\Claw 2\Bao cao - Hanh chinh\BAOCAOTONGHOP\HTML\KPH_TongHop_0508"
CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
TMP = os.path.join(os.environ["LOCALAPPDATA"], "Temp", "kph_tth270")
os.makedirs(TMP, exist_ok=True)
h = io.open(os.path.join(CL2, "index.html"), encoding="utf-8").read()
soup = BeautifulSoup(h, "html.parser")
blk = [b for b in soup.select("div.inc") if b.get("id") == "tienhung-tth270"][0]
style = soup.find("style")
blk_html = str(blk).replace('loading="lazy"', 'loading="eager"')
page = f"""<!DOCTYPE html><html lang="vi"><head><meta charset="utf-8">{style}
<style>body{{background:#f4f7fb;padding:18px}}.inc-body{{display:block !important}}</style>
</head><body><div style="max-width:1100px;margin:0 auto">{blk_html}
<script>window.addEventListener('load',function(){{
 var im=document.querySelectorAll('#tienhung-tth270 img');
 setTimeout(function(){{document.body.setAttribute('data-img',JSON.stringify(Array.from(im).map(function(i){{return i.naturalWidth+'x'+i.naturalHeight;}})));}},4000);
}});</script></body></html>"""
p = os.path.join(TMP, "rieng_tth270.html")
io.open(p, "w", encoding="utf-8").write(page)
url = "file:///" + p.replace("\\", "/").replace(" ", "%20")
r = subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--no-first-run", "--virtual-time-budget=12000",
                    "--dump-dom", f"--user-data-dir={os.path.join(TMP,'profR')}", url],
                   capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300)
m = re.search(r'data-img="([^"]*)"', r.stdout or "")
print("ảnh tải được (naturalWxH):", (m.group(1) if m else "?").replace("&quot;", '"'))
out = os.path.join(TMP, "rieng_tth270.png")
subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run",
                f"--screenshot={out}", "--window-size=1200,2600", "--virtual-time-budget=12000",
                f"--user-data-dir={os.path.join(TMP,'profR')}", url], capture_output=True, timeout=300)
print("ảnh chụp:", out, os.path.getsize(out)//1024, "KB")
