# -*- coding: utf-8 -*-
r"""B43: xác định CHÍNH XÁC nơi lưu 'bài học ở các nhà máy' — đường dẫn thật + số dòng + mẫu."""
import glob, os, sqlite3

print('=== 1. Vị trí thật các CSDL (bỏ bản _BAN_GIAO / _backup) ===')
for p in sorted(glob.glob(r'C:\Claw 2\Nghien cuu\**\CSDL*.db', recursive=True)) + [r'C:\c\deepseek-harness\claw2-db\btchem.db']:
    if '_BAN_GIAO' in p or '_backup' in p or '\\bak' in p:
        continue
    print('   %-88s %8.2f MB  (sửa %s)' % (p, os.path.getsize(p) / 1048576,
          __import__('datetime').datetime.fromtimestamp(os.path.getmtime(p)).strftime('%d/%m/%Y %H:%M')))

CSDLC = r'C:\Claw 2\Nghien cuu\Du-an-C-Kinh-nghiem-KH\CSDLC.db'
if not os.path.exists(CSDLC):
    c = glob.glob(r'C:\Claw 2\**\CSDLC.db', recursive=True)
    CSDLC = [x for x in c if '_BAN_GIAO' not in x and '_backup' not in x][0]
print()
print('=== 2. CSDLC.db -> bảng kinh_nghiem:', CSDLC)
c = sqlite3.connect('file:%s?mode=ro' % CSDLC.replace('\\', '/'), uri=True)
print('   tổng dòng kinh_nghiem:', c.execute('select count(*) from kinh_nghiem').fetchone()[0])
print('   có cột khách hàng/nhà máy:', [r[1] for r in c.execute('pragma table_info(kinh_nghiem)')])
print('   phân theo trạng thái:', c.execute('select trang_thai, count(*) from kinh_nghiem group by 1 order by 2 desc').fetchall())
print('   mẫu 4 dòng (chủ đề | hiện tượng | cách xử lý):')
for r in c.execute('select chu_de, hien_tuong, cach_xu_ly from kinh_nghiem where ifnull(chu_de,"")<>"" order by id desc limit 4'):
    print('     -', str(r[0])[:70], '|', str(r[1])[:60], '|', str(r[2])[:60])
try:
    print('   số khách hàng được gắn bài học:', c.execute('select count(distinct khach_hang_id) from kinh_nghiem').fetchone()[0])
except Exception as e:
    print('  ', e)
c.close()

print()
print('=== 3. btchem.db -> bảng su_co_kph (vụ việc KPH = bài học nhà máy) ===')
B = r'C:\c\deepseek-harness\claw2-db\btchem.db'
c = sqlite3.connect('file:%s?mode=ro' % B.replace('\\', '/'), uri=True)
print('   tổng vụ việc:', c.execute('select count(*) from su_co_kph').fetchone()[0])
print('   theo nhà máy (top 8):')
q = ('select ifnull(n.ten,"(chưa rõ)") ten, count(*) c from su_co_kph s left join nha_may n on n.id=s.nha_may_id '
     'group by 1 order by c desc limit 8')
for r in c.execute(q):
    print('     %-34s %d vụ' % (r[0], r[1]))
print('   mẫu 3 vụ mới nhất (tên vụ | loại sai | nguyên nhân | phương án):')
for r in c.execute('select ten_vu_viec, loai_sai, nguyen_nhan, phuong_an_xu_ly from su_co_kph order by id desc limit 3'):
    print('     -', ' | '.join(str(x)[:52] for x in r))
print('   bảng khác chứa bài học: bao_cao_sx.tinh_hinh_su_co =',
      c.execute("select count(*) from bao_cao_sx where ifnull(tinh_hinh_su_co,'')<>''").fetchone()[0], 'dòng có nội dung sự cố')
print('   bao_cao_kt_tuan =', c.execute('select count(*) from bao_cao_kt_tuan').fetchone()[0], 'dòng báo cáo kỹ thuật tuần')
c.close()

print()
print('=== 4. Thư mục bài học kỹ thuật trong QC ===')
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('   %s  (%d mục)' % (d, len(fs)))
        for f in fs[:12]:
            fp = os.path.join(d, f)
            print('     - %-62s %s' % (f[:62], ('%d B' % os.path.getsize(fp)) if os.path.isfile(fp) else '[thư mục]'))
    else:
        print('   (không có thư mục) %s' % d)
