# -*- coding: utf-8 -*-
r"""B66: lưu 2 file anh vừa gửi (w41.xlsx, KQM 41.xlsx) vào thư mục chuẩn + soi cấu trúc + liệt kê artefact T40."""
import glob, hashlib, os, shutil, time, zipfile

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

moi = sorted([p for p in glob.glob(os.path.join(DOC, '*'))
              if os.path.isfile(p) and os.path.getmtime(p) > time.time() - 1800], key=os.path.getmtime)
print('  === file mới trong cache ===')
for p in moi:
    print('   %s  %9d B  %s' % (time.strftime('%H:%M', time.localtime(os.path.getmtime(p))), os.path.getsize(p), os.path.basename(p)[:70]))

print()
print('  === lưu vào thư mục chuẩn ===')
for p in moi:
    if not p.lower().endswith('.xlsx'):
        continue
    goc = os.path.basename(p).split('_', 2)[-1]
    # chuẩn hoá tên đích theo quy ước
    low = goc.lower().replace(' ', '')
    if low.startswith('w41'):
        ten = 'W41.xlsx'
    elif 'kqm' in low or 'kếtquả' in goc.lower():
        ten = 'KẾT QUẢ MẪU TUẦN 41.xlsx'
    else:
        ten = goc
    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Ó %-34s | %s' % (ten, 'trùng md5' if same else 'KHÁC → lưu bản (2)'))
        if not same:
            shutil.copy2(p, os.path.join(D, ten.replace('.xlsx', ' (2).xlsx')))
    else:
        shutil.copy2(p, dich)
        print('   đã lưu: %-34s (%d B)' % (ten, os.path.getsize(dich)))

print()
print('  === SOI CẤU TRÚC 3 FILE TUẦN 41 ===')
import openpyxl
for ten in ('TUẦN 41 (05.10-11.10).xlsx', 'KẾT QUẢ MẪU TUẦN 41.xlsx', 'W41.xlsx'):
    p = os.path.join(D, ten)
    if not os.path.exists(p):
        print('   %-34s KHÔNG THẤY' % ten); continue
    wb = openpyxl.load_workbook(p, read_only=True, data_only=True)
    print('   --- %s (%d B) | %d sheet: %s' % (ten, os.path.getsize(p), len(wb.sheetnames), wb.sheetnames[:8]))
    for sn in wb.sheetnames[:6]:
        ws = wb[sn]
        n = sum(1 for r in ws.iter_rows(values_only=True) if any(c not in (None, '') for c in r))
        dong_dau = None
        for r in ws.iter_rows(values_only=True):
            if any(c not in (None, '') for c in r):
                dong_dau = [str(c)[:16] for c in r if c not in (None, '')][:8]
                break
        print('      sheet %-18s dòng có dữ liệu: %-5d | dòng đầu: %s' % (str(sn)[:18], n, dong_dau))
    wb.close()

print()
print('  === artefact tuần TRƯỚC (T40) trong "da lam sach" + script ===')
for d in (D, os.path.join(D, 'da lam sach')):
    if not os.path.isdir(d):
        continue
    for f in sorted(os.listdir(d), key=lambda x: os.path.getmtime(os.path.join(d, x)), reverse=True)[:12]:
        p = os.path.join(d, f)
        if 'tuan40' in f.lower() or 't40' in f.lower() or 'Tuan_40' in f:
            print('   %-38s %s' % (f[:38], ('%d B' % os.path.getsize(p)) if os.path.isfile(p) else '[thư mục]'))
print('   script clean_and_merge_T40:', [os.path.basename(x) for x in glob.glob(os.path.join(D, 'clean_and_merge*.py'))][-3:])
