# -*- coding: utf-8 -*-
"""Tạo bản sao CSDL BTchem để gửi + kiểm chứng, và dò xem file nào chứa dữ liệu KPH."""
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)
NGAY = time.strftime('%Y-%m-%d')
DST = os.path.join(OUTDIR, 'CSDL_BTCHEM_%s.db' % NGAY)


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Ò FILE CHỨA DỮ LIỆU KPH ===')
for p in sorted(glob.glob(r'C:\c\deepseek-harness\claw2-db\*.db')) + sorted(glob.glob(r'C:\c\deepseek-harness\**\*.db', recursive=True))[:40]:
    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('   %-70s %s (%d dòng)' % (os.path.basename(p), k, n))
        c.close()
    except Exception:
        pass

print()
print('=== 2. TẠO BẢN SAO CSDL GỬI ĐI ===')
shutil.copy2(SRC, DST)
print('   gốc :', SRC, os.path.getsize(SRC), 'byte | md5', md5(SRC))
print('   sao :', DST, os.path.getsize(DST), 'byte | md5', md5(DST))
print('   trùng byte với bản gốc:', md5(SRC) == md5(DST))

c = sqlite3.connect(DST)
print('   integrity:', c.execute('pragma integrity_check').fetchone()[0])
print('   các bảng có dữ liệu:')
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()
print('SẴN SÀNG GỬI:', DST)
