# -*- coding: utf-8 -*-
r"""B41: tìm nơi lưu BÀI HỌC (nhà máy) — soi bảng trong các CSDL + thư mục bài học."""
import os, sqlite3, glob

DB = [
    r'C:\c\deepseek-harness\claw2-db\btchem.db',
    r'C:\Claw 2\Nghien cuu\Du-an-A-Quy-trinh-son\CSDLA.db',
    r'C:\Claw 2\Nghien cuu\Du-an-B-He-mau-Stain-Glaze\CSDLB.db',
    r'C:\Claw 2\Nghien cuu\Du-an-C-Kinh-nghiem-KH\CSDLC.db',
    r'C:\Claw 2\Nghien cuu\Du-an-D-Ho-so-go\CSDLD.db',
]
# quét thêm mọi .db trong Claw 2
for p in glob.glob(r'C:\Claw 2\**\*.db', recursive=True):
    if p not in DB:
        DB.append(p)

for p in DB:
    if not os.path.exists(p):
        print('  (không thấy) %s' % p); continue
    try:
        c = sqlite3.connect('file:%s?mode=ro' % p.replace('\\', '/'), uri=True)
        t = [r[0] for r in c.execute("select name from sqlite_master where type='table' order by name")]
        print('=== %s  (%.2f MB, %d bảng)' % (p, os.path.getsize(p) / 1048576, len(t)))
        for ten in t:
            try:
                n = c.execute('select count(*) from "%s"' % ten).fetchone()[0]
            except Exception:
                n = '?'
            canh = ''
            low = ten.lower()
            if any(k in low for k in ('bai_hoc', 'baihoc', 'lesson', 'kinh_nghiem', 'kn_', 'ghi_chu', 'note')):
                canh = '   <== NGHI BÀI HỌC'
            cols = ''
            if canh:
                cols = ' | cột: ' + ', '.join(r[1] for r in c.execute('pragma table_info("%s")' % ten))
            print('   %-34s %6s dòng%s%s' % (ten, n, canh, cols))
        c.close()
    except Exception as e:
        print('=== %s LỖI: %s' % (p, str(e)[:80]))

print()
for d in (r'C:\Claw 2\QC\Bai-hoc-ky-thuat', r'C:\Claw 2\Bai-hoc-ky-thuat'):
    if os.path.isdir(d):
        fs = sorted(os.listdir(d))
        print('=== THƯ MỤC %s (%d mục)' % (d, len(fs)))
        for f in fs[:14]:
            fp = os.path.join(d, f)
            print('   %-58s %s' % (f[:58], ('%d B' % os.path.getsize(fp)) if os.path.isfile(fp) else '[thư mục]'))
        if len(fs) > 14:
            print('   ... và %d mục nữa' % (len(fs) - 14))
