# -*- coding: utf-8 -*-
"""Xuất GÓI KIẾN THỨC đã huấn luyện trong CSDLA (luật huấn luyện + quy trình chuẩn + bộ 34 bước) để nạp vào bước 2 của quy trình AGY."""
import io, os, sqlite3, time

D = r'C:\Claw 2\Nghien cuu\Du-an-A-Quy-trinh-son'
DB = os.path.join(D, 'CSDLA.db')
OUT = os.path.join(D, 'CSDLA_KIEN_THUC_HUAN_LUYEN.md')

c = sqlite3.connect(DB)
c.row_factory = sqlite3.Row
L = []
L.append('# GÓI KIẾN THỨC ĐÃ HUẤN LUYỆN (trích từ CSDLA.db) — ngày %s' % time.strftime('%d/%m/%Y'))
L.append('')
L.append('> Dùng làm ĐẦU VÀO BẮT BUỘC cho bước 2 (áp kiến thức vào phân tích của AGY để ra quy trình đề nghị chuẩn).')
L.append('')
L.append('## A. LUẬT HUẤN LUYỆN CỦA CHỦ DỰ ÁN (bảng `huan_luyen`, %d dòng)'
         % c.execute('select count(*) from huan_luyen').fetchone()[0])
L.append('')
L.append('| # | Nhóm | Nguyên văn chủ dự án | Quy tắc áp dụng | Phạm vi |')
L.append('|:--:|---|---|---|---|')
for r in c.execute('select * from huan_luyen order by nhom, id'):
    L.append('| %d | %s | *“%s”* | %s | %s |' % (r['id'], r['nhom'], r['nguyen_van'], r['quy_tac'], r['pham_vi']))
L.append('')
L.append('## B. QUY TRÌNH CHUẨN ĐÃ CHỐT (bảng `quy_trinh` + `buoc_quy_trinh`)')
L.append('')
for q in c.execute("select * from quy_trinh where loai like '%chuẩn%' order by id"):
    L.append('### %s (id %d · hệ %s · %s bước · %s)' % (q['ten'], q['id'], q['he_son'], q['so_buoc'], q['ngay_tai_lieu']))
    L.append('')
    L.append('%s' % (q['mo_ta'] or ''))
    L.append('')
    for b in c.execute('select * from buoc_quy_trinh where quy_trinh_id=? order by thu_tu', (q['id'],)):
        L.append('- **[Bước chuẩn %s]** %s' % (b['buoc_chuan_so'], b['buoc_nguyen_van']))
    L.append('')
L.append('## C. BỘ 34 BƯỚC CHUẨN (dùng đúng số + tên chuẩn)')
L.append('')
L.append('| Số | Tên (VI) | Tên (EN) |')
L.append('|:--:|---|---|')
for b in c.execute('select * from buoc_chuan order by so'):
    L.append('| %s | %s | %s |' % (b['so'], b['ten_vi'], b['ten_en'] or ''))
L.append('')
L.append('## D. THƯ VIỆN QUY TRÌNH CHUẨN CÔNG TY (QT_*) — chuỗi bước để đối chiếu')
L.append('')
for q in c.execute("select id, ten, he_son, so_buoc from quy_trinh where ten like 'QT_%' order by id"):
    chuoi = '→'.join(str(x[0]) for x in c.execute('select buoc_chuan_so from buoc_quy_trinh where quy_trinh_id=? order by thu_tu', (q['id'],)))
    L.append('- **%s** (id %s · %s · %s bước): `%s`' % (q['ten'], q['id'], q['he_son'], q['so_buoc'], chuoi))
L.append('')
io.open(OUT, 'w', encoding='utf-8', newline='').write('\n'.join(L) + '\n')
print('gói kiến thức:', os.path.getsize(OUT), 'byte |', len(L), 'dòng')
print('gồm:', c.execute('select count(*) from huan_luyen').fetchone()[0], 'luật huấn luyện ·',
      c.execute('select count(*) from buoc_chuan').fetchone()[0], 'bước chuẩn ·',
      c.execute("select count(*) from quy_trinh where ten like 'QT_%'").fetchone()[0], 'QT_ công ty ·',
      c.execute("select count(*) from quy_trinh where loai like '%chuẩn%'").fetchone()[0], 'quy trình chuẩn')
c.close()
