# -*- coding: utf-8 -*-
"""B26: tạo _MANIFEST.txt (sha256 + danh sách file) rồi nén bộ bàn giao thành 1 file ZIP."""
import hashlib, os, zipfile, datetime

BO = r'C:\Claw 2\_BAN_GIAO_APP_LINUX\BAN_GIAO_APP_LINUX'
ZIP = r'C:\Claw 2\_BAN_GIAO_APP_LINUX\BAN_GIAO_APP_LINUX_%s.zip' % datetime.date.today().strftime('%Y%m%d')


def sha(p, n=16):
    h = hashlib.sha256()
    with open(p, 'rb') as f:
        for b in iter(lambda: f.read(1 << 16), b''):
            h.update(b)
    return h.hexdigest()[:n]


ds = []
for root, dirs, fs in os.walk(BO):
    dirs[:] = [d for d in dirs if d not in ('__pycache__',)]
    for f in sorted(fs):
        p = os.path.join(root, f)
        ds.append((os.path.relpath(p, BO).replace('\\', '/'), os.path.getsize(p), sha(p)))
ds.sort()

# checksum các CSDL (để đối chiếu khi copy sang máy khác)
db = [x for x in ds if x[0].startswith('data/')]

lines = []
lines.append('BỘ BÀN GIAO APP QUY TRÌNH SƠN & PHA MÀU — CHO MÁY LINUX + AGENT KHÁC')
lines.append('Tạo lúc: %s (giờ VN)' % datetime.datetime.now().strftime('%d/%m/%Y %H:%M'))
lines.append('Nguồn: %s' % BO)
lines.append('Cách dùng: đọc HUONG_DAN_CAI_DAT.md TRƯỚC, rồi: bash cai_dat/cai_dat.sh')
lines.append('')
lines.append('== 3 APP ==')
lines.append('  apps/hlqt   — HLQT: huấn luyện QUY TRÌNH sơn (CSDL A) — cổng 8100')
lines.append('  apps/calib  — CALIB: huấn luyện/hiệu chỉnh HỆ MÀU (CSDL B) — cổng 8099')
lines.append('  apps/lab    — Agent-Lab: đề nghị quy trình + công thức pha màu (A/B/C/D) — cổng 8098')
lines.append('')
lines.append('== CSDL (đối chiếu sha256 sau khi copy sang máy mới) ==')
for ten, n, h in db:
    lines.append('  %-16s %9d B  sha256:%s' % (ten, n, h))
lines.append('')
lines.append('== DANH SÁCH FILE (%d) ==' % len(ds))
for ten, n, h in ds:
    lines.append('  %-56s %9d B  %s' % (ten, n, h))
open(os.path.join(BO, '_MANIFEST.txt'), 'w', encoding='utf-8').write('\n'.join(lines) + '\n')
print('  đã ghi _MANIFEST.txt (%d file)' % len(ds))

# nén
if os.path.exists(ZIP):
    os.remove(ZIP)
with zipfile.ZipFile(ZIP, 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as z:
    for ten, n, h in ds + [('_MANIFEST.txt', 0, '')]:
        p = os.path.join(BO, ten.replace('/', os.sep))
        z.write(p, 'BAN_GIAO_APP_LINUX/' + ten)
print('  ZIP:', ZIP)
print('  kích thước:', os.path.getsize(ZIP), 'B (%.2f MB)' % (os.path.getsize(ZIP) / 1048576))
print('  sha256 zip:', sha(ZIP, 64))

with zipfile.ZipFile(ZIP) as z:
    loi = z.testzip()
    print('  kiểm toàn vẹn:', 'OK' if loi is None else 'LỖI ở ' + str(loi))
    print('  số file trong zip:', len(z.namelist()))
