# -*- coding: utf-8 -*-
"""B29: gom ảnh Lộc QC 10/10 anh gửi qua Telegram — lấy ĐÚNG LÔ theo mtime, khử trùng md5."""
import glob, hashlib, os, shutil, time

CACHE = os.path.join(os.environ['LOCALAPPDATA'], 'hermes', 'cache', 'images')
DICH = r'C:\Claw 2\QC\images\_loc_1010'
os.makedirs(DICH, exist_ok=True)

CANH = os.path.join(CACHE, 'img_7f8ecf60fcd4.jpg')
print('  ảnh anh gửi:', 'CÓ' if os.path.exists(CANH) else 'KHÔNG THẤY', CANH)
mt = os.path.getmtime(CANH)
print('  mtime: %s' % time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(mt)))
print()
print('  === mọi ảnh trong cache (mới nhất 12) ===')
ds = sorted(glob.glob(os.path.join(CACHE, 'img_*.jpg')), key=os.path.getmtime, reverse=True)[:12]
for p in ds:
    print('   %-22s %8d B  %s  %s' % (os.path.basename(p), os.path.getsize(p),
          time.strftime('%d/%m %H:%M:%S', time.localtime(os.path.getmtime(p))),
          '<<< lô này' if abs(os.path.getmtime(p) - mt) < 90 else ''))
print()
# lấy cả lô cùng phút (±90 giây quanh ảnh anh gửi)
lo = [p for p in glob.glob(os.path.join(CACHE, 'img_*.jpg')) if abs(os.path.getmtime(p) - mt) < 90]
lo.sort(key=os.path.getmtime)
print('  ảnh trong lô (%d):' % len(lo))
them = 0
seen = {}
for i, p in enumerate(lo, 1):
    h = hashlib.md5(open(p, 'rb').read()).hexdigest()
    ten = 'loc_1010_%02d.jpg' % i
    dich = os.path.join(DICH, ten)
    if h in seen:
        print('   %-20s TRÙNG md5 với %s -> bỏ' % (os.path.basename(p), seen[h])); continue
    seen[h] = ten
    shutil.copy2(p, dich)
    them += 1
    print('   %-20s -> %-18s %8d B  md5 %s' % (os.path.basename(p), ten, os.path.getsize(dich), h[:10]))
print()
print('  đã gom %d ảnh vào %s' % (them, DICH))
for f in sorted(os.listdir(DICH)):
    print('   %-22s %8d B' % (f, os.path.getsize(os.path.join(DICH, f))))
