# -*- coding: utf-8 -*-
r"""B64: nhận file báo cáo làm mẫu tuần 41 -> copy vào thư mục chuẩn (không ghi đè) + soi cấu trúc."""
import glob, hashlib, os, shutil, zipfile, datetime

DOC = os.path.join(os.environ['LOCALAPPDATA'], 'hermes', 'cache', 'documents')
D = r'C:\Claw 2\Bao cao - Hanh chinh\Bao cao lam mau'
os.makedirs(D, exist_ok=True)

print('  === file trong cache documents (30 phút qua) ===')
moi = sorted([p for p in glob.glob(os.path.join(DOC, '*')) if os.path.isfile(p) and os.path.getmtime(p) > __import__('time').time() - 1800],
             key=os.path.getmtime)
for p in moi:
    print('   %s  %9d B  %s' % (datetime.datetime.fromtimestamp(os.path.getmtime(p)).strftime('%d/%m %H:%M'), os.path.getsize(p), os.path.basename(p)[:78]))

print()
print('  === copy vào thư mục chuẩn (không ghi đè) ===')
for p in moi:
    if not p.lower().endswith(('.xlsx', '.xls')):
        continue
    ten = os.path.basename(p).split('_', 2)[-1]          # bỏ tiền tố doc_<hash>_
    dich = os.path.join(D, ten)
    if os.path.exists(dich):
        same = hashlib.md5(open(p, 'rb').read()).hexdigest() == hashlib.md5(open(dich, 'rb').read()).hexdigest()
        print('   ĐÃ CÓ %s — %s (không copy)' % (ten[:60], 'trùng md5' if same else 'KHÁC nội dung → kiểm tay'))
        continue
    shutil.copy2(p, dich)
    print('   đã lưu: %s  (%d B)' % (ten, os.path.getsize(dich)))

print()
print('  === SOI CẤU TRÚC từng file mới ===')
for p in moi:
    if not p.lower().endswith(('.xlsx', '.xls')):
        continue
    ten = os.path.basename(p).split('_', 2)[-1]
    dich = os.path.join(D, ten)
    print('   --- %s (%d B) | zip hợp lệ: %s' % (ten, os.path.getsize(dich), zipfile.is_zipfile(dich)))
    try:
        import openpyxl
        wb = openpyxl.load_workbook(dich, read_only=True, data_only=True)
        print('      sheetnames (%d): %s' % (len(wb.sheetnames), wb.sheetnames[:12]))
        for sn in wb.sheetnames:
            ws = wb[sn]
            n = 0
            for r in ws.iter_rows(values_only=True):
                if any(c not in (None, '') for c in r):
                    n += 1
            print('      sheet %-16s dòng có dữ liệu: %d' % (sn[:16], n))
        wb.close()
    except Exception as e:
        print('      LỖI đọc:', str(e)[:120])
