# -*- coding: utf-8 -*-
r"""B179b: trích text + bảng của DOCX KPH tuần 3 (tự dò tên file theo tiền tố)."""
import io, os, shutil
from docx import Document

D = r'C:\Users\admin\AppData\Local\hermes\cache\documents'
ten = [f for f in os.listdir(D) if f.startswith('doc_b568ba2680ac')]
assert ten, 'khong thay file docx'
src = os.path.join(D, ten[0])
RA = r'C:\Claw 2\QC\_kph_tuan3_1010'
os.makedirs(RA, exist_ok=True)
dst = os.path.join(RA, 'THANG10_TUAN3.docx')
shutil.copy2(src, dst)
d = Document(dst)
ra = []
for i, p in enumerate(d.paragraphs, 1):
    t = (p.text or '').strip()
    if t:
        ra.append('[P%03d %s] %s' % (i, p.style.name, t))
ra.append('=== BANG: %d ===' % len(d.tables))
for ti, tb in enumerate(d.tables, 1):
    ra.append('--- Bang %d: %d hang x %d cot' % (ti, len(tb.rows), len(tb.columns)))
    for ri, row in enumerate(tb.rows, 1):
        o = ' | '.join((c.text or '').replace('\n', ' / ').strip() for c in row.cells)
        ra.append(('  r%02d | ' % ri) + o)
txt = '\n'.join(ra)
io.open(os.path.join(RA, 'NOI_DUNG.txt'), 'w', encoding='utf-8').write(txt)
print('  nguon: %s (%d byte)' % (ten[0], os.path.getsize(src)))
print('  %d doan | %d bang | %d ky tu -> NOI_DUNG.txt' % (len(d.paragraphs), len(d.tables), len(txt)))
