# -*- coding: utf-8 -*-
"""Copy 2 file bao cao mau T40 tu cache/documents vao thu muc du an (khong ghi de) + kiem chung."""
import glob, os, shutil, zipfile

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

pat = ['*TU*N 40*.xlsx', '*K*T QU* M*U TU*N 40*.xlsx']
found = []
for p in pat:
    found += glob.glob(os.path.join(DOC, p))
found = sorted(set(found))
print('tim thay trong cache:', [os.path.basename(f) for f in found])

for f in found:
    b = os.path.basename(f)
    b = b.split('_', 2)[2] if b.startswith('doc_') and b.count('_') >= 2 else b
    dst = os.path.join(DEST, b)
    if os.path.exists(dst):
        print('  DA CO (khong ghi de):', b, os.path.getsize(dst))
        continue
    shutil.copy2(f, dst)
    print('  da luu:', b, os.path.getsize(dst), 'byte')

print()
print('=== kiem chung file trong du an ===')
for f in sorted(glob.glob(os.path.join(DEST, '*40*.xlsx'))):
    b = os.path.basename(f)
    print('-', b, os.path.getsize(f), 'byte | zip:', zipfile.is_zipfile(f))
    try:
        import openpyxl
        wb = openpyxl.load_workbook(f, read_only=True, data_only=True)
        print('   sheets:', wb.sheetnames[:6], '(%d)' % len(wb.sheetnames))
        ws = wb[wb.sheetnames[0]]
        n = 0
        last = 0
        for i, row in enumerate(ws.iter_rows(values_only=True), start=1):
            if any(c is not None and str(c).strip() != '' for c in row):
                n += 1
                last = i
            if i > 6000 and 'W' not in b[:3]:
                break
        print('   sheet dau:', ws.title, '| so dong co du lieu:', n, '| dong cuoi co du lieu:', last)
        wb.close()
    except Exception as e:
        print('   loi doc:', e)
