# -*- coding: utf-8 -*-
"""Ghép mục QC ngày 07/10/2026 (Lộc) vào Locqc.md — backup + ghi nguyên tử + kiểm chứng, rồi xuất DOCX."""
import os, shutil, subprocess, sys, zipfile

QC = r'C:\Claw 2\QC'
F = os.path.join(QC, 'Locqc.md')
SRC = os.path.join(QC, '_muc_loc_0710.md')
NGAY = '20261007'
BK_DIR = os.path.join(QC, NGAY, 'BACKUP_MD', 'Nhan su tham gia')
os.makedirs(BK_DIR, exist_ok=True)
TIEU_DE = '# BÁO CÁO QC — CẬP NHẬT 07/10/2026: Kiểm tra màu **MK 12/17 H** theo quy trình sản xuất thực tế'

raw = open(F, 'rb').read()
assert len(raw) > 100000, 'file QC qua nho (%d byte) — DUNG' % len(raw)
s = raw.decode('utf-8')
if TIEU_DE in s:
    sys.exit('DỪNG: mục 07/10/2026 (Lộc) đã có trong file')

bk = os.path.join(BK_DIR, 'QC__Locqc.md')
if os.path.exists(bk):
    bk = os.path.join(BK_DIR, 'QC__Locqc.md_lan2_0710')
shutil.copy2(F, bk)
print('backup:', bk, os.path.getsize(bk), 'byte')

muc = open(SRC, encoding='utf-8').read().rstrip('\n')
NL = '\r\n'
moi = raw.rstrip(b'\r\n') + (NL + NL + muc.replace('\n', NL)).encode('utf-8')
tmp = F + '.tmp_ghi'
open(tmp, 'wb').write(moi)
os.replace(tmp, F)

moi_raw = open(F, 'rb').read()
s2 = moi_raw.decode('utf-8')
print('\n=== KIỂM CHỨNG SAU KHI GHI ===')
print('   byte: %d → %d (+%d)' % (len(raw), len(moi_raw), len(moi_raw) - len(raw)))
print('   backup là TIỀN TỐ của bản mới:', moi_raw.startswith(open(bk, 'rb').read().rstrip(b'\r\n')))
print('   tiêu đề mục mới xuất hiện:', s2.count(TIEU_DE), 'lần')
print('   số ảnh chèn (images/loc_0710_):', s2.count('images/loc_0710_'))
print('   CRLF:', s2.count('\r\n'), '| LF-only:', s2.count('\n') - s2.count('\r\n'))

docx = os.path.join(QC, 'BAO_CAO_QC_07-10-2026_Bui_Thien_Loc.docx')
p = subprocess.run([sys.executable, os.path.join(QC, '_md2docx.py'), SRC, docx, QC],
                   capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=QC)
print('\n=== XUẤT DOCX ===')
print('   rc =', p.returncode, '|', (p.stdout or '').strip()[-200:], (p.stderr or '').strip()[-200:])
if os.path.exists(docx):
    print('   DOCX:', docx, os.path.getsize(docx), 'byte')
    z = zipfile.ZipFile(docx)
    media = [n for n in z.namelist() if n.startswith('word/media/')]
    print('   ảnh nhúng:', len(media))
    from docx import Document
    d = Document(docx)
    txt = '\n'.join(x.text for x in d.paragraphs) + '\n' + '\n'.join(
        c.text for t in d.tables for r in t.rows for c in r.cells)
    print('   đoạn:', len(d.paragraphs), '| bảng:', len(d.tables), '| ảnh:', len(d.inline_shapes))
    for k in ['MK 12/17', 'SW6', '2203', '3012', '7 loại MDF', 'Oak', 'Beech', 'KPH 44-26', 'BÙI THIÊN LỘC']:
        print('      có "%s": %s' % (k, 'CÓ' if k in txt else 'KHÔNG'))
