# -*- coding: utf-8 -*-
"""Truy CSDLA + hệ thống xem màu: bước 'Lau bột bụi' (11) có được dùng không? công thức bột nào?"""
import os, re, sqlite3

D = r'C:\Claw 2\Nghien cuu\Du-an-A-Quy-trinh-son'
c = sqlite3.connect(os.path.join(D, 'CSDLA.db'))
c.row_factory = sqlite3.Row

print('=== 1. Định nghĩa bước 11 trong bộ bước chuẩn ===')
for r in c.execute("select * from buoc_chuan where so_buoc=11 or ten like '%bột%'"):
    print('  ', dict(r))

print()
print('=== 2. Có bao nhiêu quy trình thực tế dùng bước 11 / các bước liên quan bột? ===')
cur = c.execute("select count(*) from buoc_quy_trinh where so_buoc=11")
print('   dòng buoc_quy_trinh gắn bước 11:', cur.fetchone()[0])
try:
    for r in c.execute("select bq.quy_trinh_id, bq.so_buoc, substr(bq.mo_ta,1,120) m from buoc_quy_trinh bq where bq.mo_ta like '%bột%' limit 12"):
        print('   ', dict(r))
except Exception as e:
    print('   (lỗi cột):', e)
    for r in c.execute("select * from buoc_quy_trinh limit 1"):
        print('    cột:', r.keys())

print()
print('=== 3. Mã màu / công thức / hoá chất có chữ "bột" ===')
for bang in ['cong_thuc', 'danh_muc_mau', 'quy_trinh', 'phong_cach']:
    try:
        ks = [d[1] for d in c.execute('pragma table_info(%s)' % bang)]
        for k in ks:
            for r in c.execute("select rowid, * from %s where cast(%s as text) like '%%bột%%'" % (bang, k)):
                print('   [%s.%s]' % (bang, k), dict(zip(['rowid'] + ks, r)))
    except Exception as e:
        print('   lỗi', bang, e)
c.close()

print()
print('=== 4. Trong hệ thống xem màu (HETHONGXEMMAU): chữ bột / ceruse / limed ===')
ND = os.path.join(D, 'nguon_HETHONGXEMMAU')
for f in sorted(os.listdir(ND)):
    if f.lower().endswith(('.md', '.txt')):
        t = open(os.path.join(ND, f), encoding='utf-8', errors='replace').read()
        hits = [k for k in ['bột', 'Bột', 'ceruse', 'Ceruse', 'limed', 'Limed', 'xám trắng', 'trắng xám'] if k in t]
        if hits:
            print('   %-46s %s' % (f, hits))
print('   (danh sách QT có trong thư mục QUITRINHSON:)')
p = os.path.join(ND, '_ds_quitrinhson.txt')
if os.path.exists(p):
    for l in open(p, encoding='utf-8'):
        if l.startswith('QT_'):
            print('      ', l.strip())
