# -*- coding: utf-8 -*-
"""Dọn sạch tài liệu gọn: bỏ chú thích phân tích (Mảng/L*), bỏ trích dẫn CSDLA — chỉ giữ quy trình."""
import io, os, re, shutil, subprocess
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 = os.path.join(D, 'QUY_TRINH_DE_XUAT_NAU-XAM-TRO_2026-10-06.docx')

L = io.open(MD, encoding='utf-8').read().split('\n')
out = []
for l in L:
    # bỏ chú thích in nghiêng chứa dữ liệu phân tích
    l = re.sub(r'\*\(?[^(*]*?(?:Mảng \d|L\\\*|nâu tro L|gờ vân)[^(*]*?\)?\*', '', l)
    # bỏ ngoặc chứa trích dẫn CSDLA / ID hồ sơ
    l = re.sub(r'\((?:[^()]*(?:CSDLA|ID \d|KPH)[^()]*)\)', '', l)
    l = re.sub(r'\s{2,}', ' ', l).replace(' |', '|').replace('| ', '| ')
    l = re.sub(r'\(\s*\)', '', l)
    l = re.sub(r'\s+\.', '.', l)
    out.append(l.rstrip())
io.open(MD, 'w', encoding='utf-8', newline='').write('\n'.join(out))
t = '\n'.join(out)
print('MD sau dọn:', os.path.getsize(MD), 'byte')
print('còn "Mảng":', t.count('Mảng'), '| "CSDLA":', t.count('CSDLA'), '| "KPH":', t.count('KPH'), '| "L*":', t.count('L*'))
print()
print('--- nội dung bảng PA1 (dòng 1-3) ---')
for l in out:
    if re.match(r'^\| [123] \|', l):
        print(l[:230])
        print()

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)
txt = '\n'.join(x.text for x in d.paragraphs)
for tb in d.tables:
    for r in tb.rows:
        for c in r.cells:
            txt += '\n' + c.text
print('DOCX %d byte | đoạn %d | bảng %d | ảnh %d | dòng bảng %s' % (os.path.getsize(DOCX), len(d.paragraphs), len(d.tables), len(d.inline_shapes), [len(x.rows) for x in d.tables]))
for k in ['KPH', 'CSDLA', 'Mảng', 'L*', 'zoom', 'Sồi', 'Tần bì', 'truy vết', 'QT_', 'ID 44']:
    print('   "%s": %s' % (k, 'SẠCH' if k not in txt else 'CÒN %d lần' % txt.count(k)))
out2 = os.path.join(os.environ['LOCALAPPDATA'], 'hermes', 'cache', 'gui_duan_a')
os.makedirs(out2, exist_ok=True)
shutil.copy2(DOCX, out2)
print('bản gửi:', os.path.getsize(os.path.join(out2, os.path.basename(DOCX))), 'byte')
