# -*- coding: utf-8 -*-
"""Chèn ảnh phiếu TT không phù hợp (Minh Hạnh) vào khối 39 — đặt TRƯỚC ảnh báo cáo."""
import io, os, re, shutil, sqlite3, datetime

CL2 = r"C:\Claw 2\Bao cao - Hanh chinh\BAOCAOTONGHOP\HTML\KPH_TongHop_0508"
P = os.path.join(CL2, "index.html")
IMG = os.path.join(CL2, "assets", "images")
SRC = r"C:\Users\admin\AppData\Local\hermes\cache\images\img_5470844c6c7c.jpg"
TEN = "minhhanh_mh289c_phieu_tt_1409.jpg"
STAMP = datetime.datetime.now().strftime("%Y%m%d_%H%M")

shutil.copy2(SRC, os.path.join(IMG, TEN))
print("ảnh:", TEN, os.path.getsize(os.path.join(IMG, TEN)) // 1024, "KB")

h = io.open(P, encoding="utf-8", newline="").read()
shutil.copy2(P, P.replace(".html", f".bak_{STAMP}_truoc_phieu_tt.html"))
NL = "\r\n" if "\r\n" in h else "\n"

# gallery: 2 cột trên màn lớn, 1 cột trên mobile; ảnh giữ nguyên tỷ lệ (contain)
h = h.replace('<div class="gallery" style="grid-template-columns:1fr;max-width:520px">',
              '<div class="gallery" style="grid-template-columns:repeat(auto-fit,minmax(300px,1fr));max-width:1000px">')

FIG = ('<figure class="fig"><img src="assets/images/' + TEN + '" alt="Phiếu thông tin không phù hợp (biên bản sự việc) 14/9/2026 — Minh Hạnh, SP bàn MH-289C" '
       'loading="lazy" style="height:auto;object-fit:contain"><figcaption>Phiếu TT không phù hợp ngày 14/9/2026 — khách hàng CTC, SP bàn MH-289C (hũ lưu và gỗ đều SAI; ký: Duyên)</figcaption></figure>')

i_blk = h.find('id="minhhanh-mh289c"')
assert i_blk > 0
i_gal = h.find('<div class="gallery"', i_blk)
assert i_gal > 0, "không tìm thấy gallery trong khối 39"
i_firstfig = h.find('<figure class="fig">', i_gal)
assert i_firstfig > 0
h2 = h[:i_firstfig] + FIG + NL + "          " + h[i_firstfig:]

old_src = "Ảnh kèm: bản báo cáo viết tay Phụ lục 02-QT-KT-TTKT/01 ngày 14/9/2026 (ký: Duyên)."
new_src = "Ảnh kèm: phiếu thông tin không phù hợp và bản báo cáo viết tay Phụ lục 02-QT-KT-TTKT/01, đều ngày 14/9/2026 (ký: Duyên)."
assert old_src in h2
h2 = h2.replace(old_src, new_src)

assert h2.count('class="inc"') == 39
assert h2.count("<div") == h2.count("</div>"), (h2.count("<div"), h2.count("</div>"))
assert h2.count("<figure") == h2.count("</figure>")
assert h2.count("<figcaption") == h2.count("</figcaption>")
io.open(P, "w", encoding="utf-8", newline="").write(h2)

chk = io.open(P, encoding="utf-8").read()
blk = chk[chk.find('id="minhhanh-mh289c"'):]
blk = blk[:blk.find('</section>')]
print("portal:", chk.count('class="inc"'), "khối | figure:", chk.count("<figure"), "| div cân bằng:", chk.count("<div") == chk.count("</div>"))
print("ảnh trong khối 39:", re.findall(r'assets/images/([^"]+)"', blk))

MO_THEM = (" | 16/09/2026 — Đã chèn thêm ảnh PHIẾU THÔNG TIN KHÔNG PHÙ HỢP ngày 14/9/2026 (khách hàng CTC — SP bàn MH-289C; "
           "hũ lưu và gỗ đều SAI; ký: Duyên, Tổ trưởng Kỹ thuật) vào khối 39 portal — Phòng Kỹ thuật")
k = sqlite3.connect(r"C:\Claw\Khieu Nai KHach Hang\btchem_kph.db", timeout=90, isolation_level=None)
kc = k.cursor(); kc.execute("BEGIN IMMEDIATE")
kc.execute("UPDATE ho_so_kph SET cap_nhat = cap_nhat || ? WHERE id = 825", (MO_THEM,)); kc.execute("COMMIT")
print("hồ sơ #825 cap_nhat:", kc.execute("SELECT length(cap_nhat) FROM ho_so_kph WHERE id=825").fetchone()[0], "ký tự")
k.close()
c = sqlite3.connect(r"C:\c\deepseek-harness\claw2-db\btchem.db", timeout=90, isolation_level=None)
cc = c.cursor(); cc.execute("BEGIN IMMEDIATE")
cc.execute("UPDATE su_co_kph SET mo_ta_su_co = mo_ta_su_co || ? WHERE id = 58", (MO_THEM,)); cc.execute("COMMIT")
print("su_co_kph #58 mo_ta:", cc.execute("SELECT length(mo_ta_su_co) FROM su_co_kph WHERE id=58").fetchone()[0], "ký tự")
c.close()
