# -*- coding: utf-8 -*-
"""Kiểm chứng file bước 2 của pipeline lô 05 (chỉ quy trình) + xuất DOCX có ảnh."""
import io, 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, 'QUY_TRINH_DE_XUAT_NAU-XAM-TRO_2026-10-06.md')
DOCX = MD[:-3] + '.docx'
t = io.open(MD, encoding='utf-8').read()
print('=== file bước 2 (pipeline) ===')
print('   %d byte | %d dòng' % (os.path.getsize(MD), len(t.split('\n'))))

pa = {}
for k in re.split(r'\n#{2,3} ', t):
    m = re.search(r'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('   phương án tìm thấy:', sorted(pa))
for k, v in sorted(pa.items()):
    chuoi = []
    for l in v:
        m = re.search(r'Bước (\d+)', l)
        chuoi.append(m.group(1) if m else ('KT-DM' if 'KIỂM TRA MÀU' in l else '?'))
    print('   PA %d: %d dòng | chuỗi: %s | dòng kiểm tra–dặm màu: %d'
          % (k, len(v), '→'.join(chuoi), sum(1 for l in v if 'KIỂM TRA MÀU' in l)))
tot = ''.join(sum(pa.values(), []))
MA = ['S07', 'B07', 'TBS', 'TBN', 'BT 2203', '0707', '1024H', 'PT-011', 'PT-002', '2010H', 'Titan R628', 'FD 0212',
      'SM 2802', 'PC 23', 'DL 16/19', 'KH 3900', 'OD 0408', 'OD0405', 'NC KH']
print('   mã thương mại trong bảng:', [k for k in MA if k in tot] or 'SẠCH', '| "2K" trong bảng:', any('2K' in l for l in tot))
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 bảng:', [m for m in MOC if any(m.lower() in l.lower() for l in tot)] or 'KHÔNG có')
print('   thứ tự chuẩn (PA1: 5→19→KT→9→20→33→KT→21):',
      [x for x in [''.join(re.findall(r'\d+|KT', l)) for l in pa.get(1, [])]])

print('=== quy tắc phạm vi tài liệu ===')
for k in ['KPH', 'CSDLA', 'L\\*', 'zoom', 'Mảng', 'truy vết', 'QT_', 'ID 44', 'Sồi', 'Tần bì', 'loài gỗ']:
    print('   "%s": %s' % (k, 'SẠCH' if k not in t else 'CÒN!'))
for k, mo in [('THIẾU ẢNH GỖ MỘC', 'dòng thiếu ảnh mộc'), ('mau_01.jpg', 'dòng ảnh mẫu'),
              ('KIỂM TRA MÀU', 'dòng kiểm tra–dặm màu'), ('4B', 'test 4B/5B'),
              ('khô', 'nhắc khô hoàn toàn trước khi lau')]:
    print('   %-32s %s' % (mo, 'có' if k in t else 'THIẾU'))

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

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']:
    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('   DOCX %d byte | đoạn %d | bảng %d | ảnh %d | H1 %s' % (os.path.getsize(DOCX), len(d.paragraphs), len(d.tables), len(d.inline_shapes), d.styles['Heading 1'].font.color.rgb))
print('   dòng bảng:', [len(x.rows) for x in d.tables])
print()
print('--- BẢNG PA 1 (theo pipeline) ---')
for r in (d.tables[0].rows if d.tables else []):
    print(' | '.join(c.text[:40] for c in r.cells))
o = os.path.join(os.environ['LOCALAPPDATA'], 'hermes', 'cache', 'gui_duan_a')
os.makedirs(o, exist_ok=True)
shutil.copy2(DOCX, o)
print('bản gửi:', os.path.getsize(os.path.join(o, os.path.basename(DOCX))), 'byte')
