# -*- coding: utf-8 -*-
r"""B171: Lộc 14/10 — copy 3 ảnh chèn + GHI THÊM mục vào Locqc.md + xuất DOCX + kiểm chứng đầy đủ."""
import difflib, io, os, re, shutil, subprocess, sys, zipfile

QC = r'C:\Claw 2\QC'
SOT = os.path.join(QC, 'Locqc.md')
MUC = io.open(os.path.join(QC, '_muc_loc_1410.md'), encoding='utf-8').read().rstrip('\r\n')
NGUON = os.path.join(QC, 'images', '_zalo_loc_1410')
CAN = {
    'loc1410_03_8a9637.jpg': 'loc_1410_tvt_tu-so-mau-tilo-p120_d65.jpg',
    'loc1410_11_e8db0b.jpg': 'loc_1410_tvt_phoi-tai-che-bong-tu-nhien_13-14-10.jpg',
    'loc1410_14_b7ca47.jpg': 'loc_1410_tvt_dam-son-xu-ly-loi-tray-mop.jpg',
}
for goc, dich in CAN.items():
    shutil.copy2(os.path.join(NGUON, goc), os.path.join(QC, 'images', dich))
    print('  ảnh chèn: %-52s %d byte' % (dich, os.path.getsize(os.path.join(QC, 'images', dich))))

old = io.open(SOT, encoding='utf-8', newline='').read()
print('  sổ TRƯỚC: %d byte · %d mục' % (len(old.encode('utf-8')), old.count('\n# BÁO CÁO')))
if re.search(r'\n# BÁO CÁO[^\n]*CẬP NHẬT 14/10/2026', old):
    raise SystemExit('  DỪNG: đã có mục 14/10 trong Locqc.md!')
moi = old.rstrip('\r\n') + '\n\n' + MUC + '\n'
tmp = SOT + '.tmp'
io.open(tmp, 'w', encoding='utf-8', newline='').write(moi)
os.replace(tmp, SOT)
new = io.open(SOT, encoding='utf-8', newline='').read()
print('  sổ SAU  : %d byte · %d mục' % (len(new.encode('utf-8')), new.count('\n# BÁO CÁO')))
o, n = old.split('\n'), new.split('\n')
sm = difflib.SequenceMatcher(None, o, n, autojunk=False)
rem = add = 0; first = None
for tag, i1, i2, j1, j2 in sm.get_opcodes():
    if tag in ('replace', 'delete'):
        rem += i2 - i1; first = i1 if first is None else first
    if tag in ('replace', 'insert'):
        add += j2 - j1
print('  difflib: xoá %d · thêm %d · dòng đổi đầu: %s | startswith(cũ): %s | chênh: %r'
      % (rem, add, first, new.startswith(old.rstrip('\r\n')), old[len(old.rstrip('\r\n')):]))

RA = os.path.join(QC, 'BAO_CAO_QC_14-10-2026_Bui_Thien_Loc.docx')
SCRIPT = r'C:\Users\admin\AppData\Local\hermes\skills\productivity\qc-daily-report-chain\scripts\md2docx-qc.py'
r = subprocess.run([sys.executable, SCRIPT, os.path.join(QC, '_muc_loc_1410.md'), RA, QC],
                   capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=QC, timeout=900)
print('  xuất DOCX:', (r.stdout or '').strip()[-160:])
if r.returncode != 0:
    print('  LỖI:', (r.stderr or '')[-300:])
from docx import Document
d = Document(RA)
sao = sum(p.text.count('**') for p in d.paragraphs) + sum(c.text.count('**') for t in d.tables for row in t.rows for c in row.cells)
thieu = sum(1 for p in d.paragraphs if 'thiếu ảnh' in p.text.lower())
with zipfile.ZipFile(RA) as z:
    media = [x for x in z.namelist() if x.startswith('word/media/')]
print('  DOCX: %d byte · %d đoạn · %d bảng · %d ảnh · dấu ** = %d · "thiếu ảnh" = %d'
      % (os.path.getsize(RA), len(d.paragraphs), len(d.tables), len(media), sao, thieu))
txt = '\n'.join(p.text for p in d.paragraphs) + '\n' + '\n'.join(c.text for t in d.tables for row in t.rows for c in row.cells)
for k in ('01 - 1026', 'ΔE 0,30', '0,70', '0,53', '0,65', 'Tân Việt Tiến', 'Huỳnh Công Nông', '7 cont', 'TVT 226', 'TVT 662', '7,28', '7,38'):
    print('    %-18s %s' % (k, k in txt))
