# -*- coding: utf-8 -*-
"""Kiểm chứng lô 05 (format mới: 2 phương án · ngắn gọn · kiểm tra-dặm màu) + xuất DOCX có ảnh."""
import os, re, shutil, sqlite3, subprocess, time, zipfile
from docx import Document
from docx.shared import RGBColor

D = r'C:\Claw 2\Nghien cuu\Du-an-A-Quy-trinh-son'
PY = r'C:\Users\admin\AppData\Local\hermes\hermes-agent\venv\Scripts\python.exe'
MD = os.path.join(D, 'DE_XUAT_2PA_NAU-XAM-TRO_2026-10-06.md')
DOCX = os.path.join(D, 'DE_XUAT_2PA_NAU-XAM-TRO_2026-10-06.docx')
DB = os.path.join(D, 'CSDLA.db')
t = open(MD, encoding='utf-8').read()
c = sqlite3.connect(DB)
print('=== 0. CSDLA chỉ đọc? ===')
print('   mtime', time.strftime('%H:%M:%S', time.localtime(os.path.getmtime(DB))), '| size', os.path.getsize(DB),
      '| QT %d · bước-QT %d · nguồn %d' % tuple(c.execute('select count(*) from %s' % x).fetchone()[0] for x in ['quy_trinh', 'buoc_quy_trinh', 'nguon_quet']))
c.close()

# tách bảng PA1 / PA2
khoi = re.split(r'\n### ', t)
pa = {}
for k in khoi:
    m = re.match(r'\d+\. Bảng quy trình Phương án (\d)', k)
    if m:
        pa[int(m.group(1))] = [l for l in k.split('\n') if re.match(r'^\| \d+ \|', l)]
print()
print('=== 1. Hai phương án ===')
print('   số phương án tìm thấy:', sorted(pa))
for k, v in pa.items():
    kt = sum(1 for l in v if 'KIỂM TRA MÀU' in l)
    print('   PA %d: %d dòng | dòng kiểm tra–dặm màu: %d %s' % (k, len(v), kt, 'OK' if kt else 'THIẾU'))
tot = ''.join(sum(pa.values(), []))
MA = ['S07', 'B07', 'SW2', 'TBS', 'TBN', 'TB 1501', 'BT 78H', 'BT 01', 'BT 2102', 'BT 2203', '0707', '1024H', 'Diluent',
      'QD 0408', 'TXXT', 'MP 689', 'PT-011', 'PT-002', 'TW.REC', 'PT-06', 'S01-25', '2010H', 'NC KH', 'Titan R628',
      'FD 0212', 'SM 2802', 'SM 3001', 'OD 0408', 'OD0405', 'PC 23', 'DL 16/19', 'KH 3900']
print('   mã thương mại trong 2 bảng:', [k for k in MA if k in tot] or 'SẠCH')
print('   "2K" trong 2 bảng:', any('2K' in l for l in sum(pa.values(), [])))
MOC = ['Vá trám', 'Trét lấp', 'Nâng thớ', 'chống loang màu', 'keo tràn', 'Kiểm soát độ ẩm', 'Khử bụi', 'Chà nhám bề mặt mộc']
print('   bước xử lý mộc trong 2 bảng:', [m for m in MOC if any(m.lower() in l.lower() for l in sum(pa.values(), []))] or 'KHÔNG có')

print()
print('=== 2. Quy tắc mới ===')
for k, mo in [('THIẾU ẢNH GỖ MỘC', 'dòng thiếu ảnh gỗ mộc ở đầu tài liệu'),
              ('PA 1', 'kết luận PA khuyến nghị'),
              ('khác biệt', 'dòng khác biệt chính giữa 2 PA'),
              ('ưu', 'dòng ưu/nhược'),
              ('4B', 'test cắt ca-rô 4B/5B'),
              ('Sau MỖI lần chà nhám', 'lưu ý kiểm tra–dặm màu sau chà nhám'),
              ('moc_', 'quy ước ảnh gỗ mộc moc_*'),
              ('mau_01.jpg', 'dòng ảnh mẫu trong .md')]:
    print('   %-42s %s' % (mo, 'có' if k in t else 'THIẾU'))
print('   NC %d lần | 2K %d lần | tên riêng %d | dòng tài liệu %d'
      % (t.count('NC'), t.count('2K'), sum(t.count(k) for k in ['Trendworld', 'Nguyễn Văn Tươi', 'Bình Thạnh chem', 'Nguyễn Văn Tùng']), len(t.split('\n'))))

EMO = re.compile(r'[\U0001F000-\U0001FAFF\U00002600-\U000027BF\u2190-\u21FF\u2B00-\u2BFF\uFE0F]')
found = sorted(set(EMO.findall(t)))
if found:
    t = EMO.sub('', t)
    t = re.sub(r'[ \t]+\n', '\n', t)
    open(MD, 'w', encoding='utf-8').write(t)
    print('   đã dọn ký hiệu:', found)

subprocess.run([PY, r'C:\Users\admin\AppData\Local\hermes\skills\productivity\markdown-to-docx\scripts\md2docx.py', MD, DOCX, 'full'],
               capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=D)
d = Document(DOCX)
for s in ['Heading 1', 'Heading 2', 'Heading 3', 'Heading 4']:
    try:
        d.styles[s].font.color.rgb = RGBColor(0, 0, 0)
    except Exception:
        pass
d.save(DOCX)
d = Document(DOCX)
media = [n for n in zipfile.ZipFile(DOCX).namelist() if n.startswith('word/media/')]
print()
print('   DOCX %d byte | đoạn %d | bảng %d | ảnh %d %s | H1 %s'
      % (os.path.getsize(DOCX), len(d.paragraphs), len(d.tables), len(d.inline_shapes), media, d.styles['Heading 1'].font.color.rgb))
print('   số dòng mỗi bảng:', [len(x.rows) for x in d.tables])
out = os.path.join(os.environ['LOCALAPPDATA'], 'hermes', 'cache', 'gui_duan_a')
os.makedirs(out, exist_ok=True)
shutil.copy2(DOCX, out)
print('   bản gửi:', os.path.join(out, os.path.basename(DOCX)), os.path.getsize(os.path.join(out, os.path.basename(DOCX))), 'byte')
