# -*- coding: utf-8 -*-
"""Sửa chỗ thứ 3 ghi số vụ (h2 mục 01) + kiểm tra hiển thị khối TTH270 (ép hiện)."""
import io, os, re, subprocess, json
P = r"C:\Claw 2\Bao cao - Hanh chinh\BAOCAOTONGHOP\HTML\KPH_TongHop_0508\index.html"
h = io.open(P, encoding="utf-8", newline="").read()
n_dom = h.count('class="inc"')
h2, c = re.subn(r"\(35 vụ — nhấp tiêu đề", f"({n_dom} vụ — nhấp tiêu đề", h)
print("sửa h2:", c, "chỗ | DOM:", n_dom)
assert c == 1, "⚠ số chỗ sửa không như mong đợi"
assert h2.count('class="inc"') == n_dom and h2.count("<div") == h2.count("</div>")
io.open(P, "w", encoding="utf-8", newline="").write(h2)
chk = io.open(P, encoding="utf-8").read()
print("số vụ ghi ở các chỗ:", re.findall(r"(\d+)\s*vụ việc", chk), re.findall(r"\((\d+) vụ —", chk))

# ---- kiểm tra hiển thị: ép .inc-body hiện bằng CSS + ảnh eager ----
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)
force = """<style>#tienhung-tth270 .inc-body{display:block !important}</style>
<script>window.addEventListener('load',function(){
  var b=document.getElementById('tienhung-tth270'); var imgs=b.querySelectorAll('img');
  imgs.forEach(function(i){ i.loading='eager'; });
  setTimeout(function(){
    document.body.setAttribute('data-img', JSON.stringify(Array.from(imgs).map(function(i){return i.naturalWidth+'x'+i.naturalHeight;})));
    document.body.setAttribute('data-src', JSON.stringify(Array.from(imgs).map(function(i){return i.getAttribute('src');})));
  }, 5000);
});</script>"""
p = os.path.join(TMP, "force.html")
io.open(p, "w", encoding="utf-8").write(chk.replace("</head>", force + "</head>"))
url = "file:///" + p.replace("\\", "/").replace(" ", "%20")
r = subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--no-first-run", "--virtual-time-budget=15000",
                    "--dump-dom", f"--user-data-dir={os.path.join(TMP,'profF')}", url],
                   capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300)
m = re.search(r'data-img="([^"]*)"', r.stdout or "")
m2 = re.search(r'data-src="([^"]*)"', r.stdout or "")
print("ảnh khối TTH270 (naturalWxH):", (m.group(1) if m else "?").replace("&quot;", '"'))
print("src:", (m2.group(1) if m2 else "?").replace("&quot;", '"')[:200])
out = os.path.join(TMP, "khoi_tth270_force.png")
subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run",
                f"--screenshot={out}", "--window-size=1400,1900", "--virtual-time-budget=15000",
                f"--user-data-dir={os.path.join(TMP,'profF')}",
                url + "#tienhung-tth270"], capture_output=True, timeout=300)
print("ảnh chụp:", out, os.path.getsize(out)//1024, "KB")
