# -*- coding: utf-8 -*-
"""B24: dựng cây bàn giao 3 app (HLQT/CSDL A · CALIB/CSDL B · Agent-Lab) cho máy Linux.
Copy mã nguồn + dữ liệu + tài liệu; BỎ __pycache__, viec/, _backup/, log, .bat, .ps1."""
import os, re, shutil, hashlib, json, datetime

NC = r'C:\Claw 2\Nghien cuu'
OUT = r'C:\Claw 2\_BAN_GIAO_APP_LINUX\BAN_GIAO_APP_LINUX'
if os.path.exists(OUT):
    shutil.rmtree(OUT)

DEM = {
    'hlqt': (os.path.join(NC, r'Du-an-A-Quy-trinh-son\HLQT-app'), [
        'server_hlqt.py', 'worker_hlqt.py', 'goi_kien_thuc_hlqt.py', 'HDSD_HLQT.md',
        'mat_khau.txt', 'bi_mat.txt', 'pass_hlqt.txt', 'email_bao.txt', '_nhip.json', 'Chay_HLQT.bat'],
        ['kien_thuc', '_tools']),
    'calib': (os.path.join(NC, r'Du-an-B-He-mau-Stain-Glaze\calib-app'), [
        'server_calib.py', 'worker_calib.py', 'HDSD_CALIB.md',
        'mat_khau.txt', 'bi_mat.txt', 'pass_hieu_chinh.txt', 'email_bao.txt', 'Chay_Calib.bat'],
        ['_tools']),
    'lab': (os.path.join(NC, 'Agent-Lab'), [
        'server_lab.py', 'worker_lab.py', 'dung_goi_kien_thuc.py', 'HDSD_AGENT_LAB.md',
        'mat_khau.txt', 'bi_mat.txt', 'Chay_Agent-Lab.bat'],
        ['kien_thuc', '_tools']),
}
BO = ('__pycache__', '.pyc', '_backup', 'viec', '_log', '.bak_')
DS = {  # nguồn -> đích trong data/
    os.path.join(NC, r'Du-an-A-Quy-trinh-son\CSDLA.db'): 'CSDLA.db',
    os.path.join(NC, r'Du-an-B-He-mau-Stain-Glaze\CSDLB.db'): 'CSDLB.db',
    os.path.join(NC, r'Du-an-D-Ho-so-vat-lieu\CSDLD.db'): 'CSDLD.db',
    r'C:\Claw-Zalo\CSDLC\CSDLC.db': 'CSDLC.db',
    os.path.join(NC, r'Agent-Lab\lab.db'): 'lab.db',
}
TAI_LIEU = [  # tài liệu tham chiếu đi kèm
    (os.path.join(NC, r'Du-an-A-Quy-trinh-son\CSDLA_KIEN_THUC_HUAN_LUYEN.md'), 'tai-lieu/CSDLA_KIEN_THUC_HUAN_LUYEN.md'),
    (os.path.join(NC, r'Du-an-A-Quy-trinh-son\CSDLA_BOSUNG_QT_MOC.md'), 'tai-lieu/CSDLA_BOSUNG_QT_MOC.md'),
    (os.path.join(NC, r'Du-an-D-Ho-so-vat-lieu\HDSD_CSDLD.md'), 'tai-lieu/HDSD_CSDLD.md'),
]


def bo(p):
    return any(b in p for b in BO)


n_bang = 0
for ten, (src, files, dirs) in DEM.items():
    d = os.path.join(OUT, 'apps', ten)
    os.makedirs(d, exist_ok=True)
    for f in files:
        p = os.path.join(src, f)
        if os.path.exists(p):
            shutil.copy2(p, os.path.join(d, f)); n_bang += 1
        else:
            print('   ⚠ thiếu:', ten, f)
    for sub in dirs:
        s = os.path.join(src, sub)
        if not os.path.isdir(s):
            continue
        for root, dirs_, fs in os.walk(s):
            dirs_[:] = [x for x in dirs_ if x not in ('__pycache__',)]
            for f in fs:
                p = os.path.join(root, f)
                if bo(p):
                    continue
                rel = os.path.relpath(p, src)
                dp = os.path.join(d, rel)
                os.makedirs(os.path.dirname(dp), exist_ok=True)
                shutil.copy2(p, dp); n_bang += 1

os.makedirs(os.path.join(OUT, 'data'), exist_ok=True)
for src, ten in DS.items():
    if os.path.exists(src):
        shutil.copy2(src, os.path.join(OUT, 'data', ten))
        n_bang += 1
    else:
        print('   ⚠ thiếu DB:', src)

for src, rel in TAI_LIEU:
    if os.path.exists(src):
        dp = os.path.join(OUT, rel)
        os.makedirs(os.path.dirname(dp), exist_ok=True)
        shutil.copy2(src, dp); n_bang += 1

# copy 2 script phụ trợ mà worker gọi
for src, rel in [(r'C:\Claw 2\QC\_md2docx.py', 'cai_dat/md2docx.py'),
                 (r'C:\Users\admin\AppData\Local\hermes\skills\email\gui-email-kem-file\scripts\gui_mail_kem_file.py',
                  'cai_dat/gui_mail_kem_file.py')]:
    if os.path.exists(src):
        dp = os.path.join(OUT, rel)
        os.makedirs(os.path.dirname(dp), exist_ok=True)
        shutil.copy2(src, dp); n_bang += 1
        print('   + phụ trợ:', rel, os.path.getsize(dp), 'B')
    else:
        print('   ⚠ không thấy phụ trợ:', src)

print()
print('  === CÂY BÀN GIAO ===')
for root, dirs, fs in os.walk(OUT):
    muc = os.path.relpath(root, OUT)
    if muc == '.':
        muc = ''
    for f in sorted(fs):
        p = os.path.join(root, f)
        print('   %-58s %9d B' % (os.path.join(muc, f), os.path.getsize(p)))
print()
print('  tổng file:', n_bang)
# kiểm credentials trong DB (không chứa) + thống kê bảng
import sqlite3
for tn in ('CSDLA.db', 'CSDLB.db', 'CSDLD.db', 'lab.db', 'CSDLC.db'):
    p = os.path.join(OUT, 'data', tn)
    if os.path.exists(p):
        c = sqlite3.connect(p)
        tb = [x[0] for x in c.execute("select name from sqlite_master where type='table'")]
        print('   %-10s %d bảng: %s' % (tn, len(tb), ', '.join(tb[:12])))
        c.close()
