# -*- coding: utf-8 -*-
"""Bản gọn: dò KPH trong vài thư mục chỉ định + tạo bản sao btchem.db để gửi."""
import glob, hashlib, os, shutil, sqlite3, time

SRC = r'C:\c\deepseek-harness\claw2-db\btchem.db'
OUTDIR = os.path.join(os.environ['LOCALAPPDATA'], 'hermes', 'cache', 'gui_csdl')
os.makedirs(OUTDIR, exist_ok=True)
DST = os.path.join(OUTDIR, 'CSDL_BTCHEM_%s.db' % time.strftime('%Y-%m-%d'))


def md5(p):
    h = hashlib.md5()
    with open(p, 'rb') as f:
        for b in iter(lambda: f.read(1 << 20), b''):
            h.update(b)
    return h.hexdigest()


print('=== 1. DÒ BẢNG KPH TRONG claw2-db ===')
for p in sorted(glob.glob(r'C:\c\deepseek-harness\claw2-db\*.db')):
    try:
        c = sqlite3.connect('file:%s?mode=ro' % p.replace('\\', '/'), uri=True)
        ts = [r[0] for r in c.execute("select name from sqlite_master where type='table'")]
        k = [t for t in ts if 'kph' in t.lower()]
        if k:
            n = sum(c.execute('select count(*) from "%s"' % t).fetchone()[0] for t in k)
            print('   %-34s %s (%d dòng)' % (os.path.basename(p), k, n))
        c.close()
    except Exception as e:
        print('   %-34s lỗi: %s' % (os.path.basename(p), e))

print()
print('=== 2. BẢN SAO CSDL GỬI ĐI ===')
shutil.copy2(SRC, DST)
print('   gốc:', os.path.getsize(SRC), 'byte | md5', md5(SRC))
print('   sao:', os.path.getsize(DST), 'byte | md5', md5(DST), '| trùng byte:', md5(SRC) == md5(DST))
c = sqlite3.connect(DST)
print('   integrity:', c.execute('pragma integrity_check').fetchone()[0])
tong = 0
for (t,) in c.execute("select name from sqlite_master where type='table' and name not like 'sqlite_%' order by name"):
    n = c.execute('select count(*) from "%s"' % t).fetchone()[0]
    tong += n
    print('      %-26s %6d dòng' % (t, n))
print('   TỔNG %d dòng' % tong)
c.close()
print('SẴN SÀNG GỬI:', DST)
