# -*- coding: utf-8 -*-
"""Chuyển kết quả AGY (lo10-0710\\QUY_TRINH_VA_CONG_THUC_PHA_MAU_L010.md) → DOCX trắng đen, kèm 2 ảnh mẫu + gỗ mộc."""
import os, re
from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT

DIR = r'C:\Claw 2\Nghien cuu\Du-an-A-Quy-trinh-son'
LO10 = os.path.join(DIR, 'lo10-0710')
ANH = os.path.join(LO10, 'anh_mau')
MD = os.path.join(LO10, 'QUY_TRINH_VA_CONG_THUC_PHA_MAU_L010.md')
OUT = os.path.join(LO10, 'QUY_TRINH_VA_CONG_THUC_PHA_MAU_WALNUT_2026-10-07.docx')
GUI = os.path.expandvars(r'%LOCALAPPDATA%\hermes\cache\gui_duan_a')
os.makedirs(GUI, exist_ok=True)

doc = Document()
st = doc.styles['Normal']; st.font.name = 'Times New Roman'; st.font.size = Pt(10.5)
for s in doc.sections:
    s.top_margin = s.bottom_margin = Cm(1.5); s.left_margin = s.right_margin = Cm(1.5)

h = doc.add_paragraph(); h.alignment = WD_ALIGN_PARAGRAPH.CENTER
r = h.add_run('QUY TRÌNH SƠN VÀ CÔNG THỨC PHA MÀU — MẪU GỖ MÀU NÂU ÓC CHÓ (WALNUT)')
r.bold = True; r.font.size = Pt(14); r.font.color.rgb = RGBColor(0, 0, 0)
p = doc.add_paragraph(); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.add_run('Ngày: 07/10/2026 · Độ bóng mục tiêu: mờ 10–20 GU · Phân loại theo LOẠI MÀU').font.size = Pt(9.5)

# 2 ảnh: gỗ mộc + mẫu màu
tb = doc.add_table(rows=1, cols=2); tb.alignment = WD_TABLE_ALIGNMENT.CENTER
for i, (f, cap) in enumerate([('moc_01.jpg', 'Ảnh 1 — GỖ MỘC (phôi trước khi sơn)'), ('mau_01.jpg', 'Ảnh 2 — MẪU MÀU CẦN ĐẠT')]):
    c = tb.rows[0].cells[i]
    c.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    c.paragraphs[0].add_run().add_picture(os.path.join(ANH, f), width=Cm(8.0))
    cp = c.add_paragraph(); cp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    rr = cp.add_run(cap); rr.italic = True; rr.font.size = Pt(8.5)

md = open(MD, encoding='utf-8').read().replace('HOAN TAT', '')
lines = [l.rstrip() for l in md.split('\n')]

def add_table(rows):
    if not rows:
        return
    ncol = len(rows[0])
    t = doc.add_table(rows=0, cols=ncol); t.style = 'Table Grid'
    for ri, cells in enumerate(rows):
        c = t.add_row().cells
        for i, txt in enumerate(cells):
            txt = txt.replace('**', '').strip()
            c[i].text = ''
            run = c[i].paragraphs[0].add_run(txt)
            run.font.size = Pt(8.5); run.font.color.rgb = RGBColor(0, 0, 0)
            if ri == 0:
                run.bold = True
    doc.add_paragraph()

i = 0
while i < len(lines):
    ln = lines[i].strip()
    if ln.startswith('|'):
        block = []
        while i < len(lines) and lines[i].strip().startswith('|'):
            cells = [x for x in lines[i].strip().strip('|').split('|')]
            if not all(set(x.strip()) <= set(':- ') for x in cells):
                block.append(cells)
            i += 1
        add_table(block)
        continue
    if ln.startswith('#'):
        txt = ln.lstrip('#').strip().replace('**', '')
        pp = doc.add_paragraph(); rr = pp.add_run(txt); rr.bold = True; rr.font.size = Pt(12); rr.font.color.rgb = RGBColor(0, 0, 0)
    elif re.match(r'^\d\.\d', ln):
        pp = doc.add_paragraph(); rr = pp.add_run(ln.replace('**', '')); rr.bold = True; rr.font.size = Pt(11); rr.font.color.rgb = RGBColor(0, 0, 0)
    elif ln.startswith('- '):
        pp = doc.add_paragraph(style='List Bullet'); pp.add_run(ln[2:].replace('**', '')).font.size = Pt(10)
    elif ln:
        pp = doc.add_paragraph(); pp.add_run(ln.replace('**', '')).font.size = Pt(10)
    i += 1

doc.save(OUT)
print('DOCX:', OUT, os.path.getsize(OUT), 'byte')
import shutil
shutil.copy2(OUT, os.path.join(GUI, os.path.basename(OUT)))
print('đã copy sang', GUI, os.path.getsize(os.path.join(GUI, os.path.basename(OUT))), 'byte')
d2 = Document(OUT)
print('kiểm tra: đoạn %d · bảng %d · ảnh %d' % (len(d2.paragraphs), len(d2.tables),
      sum(1 for s in d2.inline_shapes)))
txt = '\n'.join(p.text for p in d2.paragraphs) + '\n' + '\n'.join(c.text for t in d2.tables for row in t.rows for c in row.cells)
for k in ['VM334', 'Y82', 'BLACK 56', '645', 'KIỂM TRA MÀU', 'DYE', 'NC', 'PU', 'UV']:
    print('   có "%s": %s' % (k, 'CÓ' if k in txt else 'không'))
