# -*- coding: utf-8 -*-
r"""B54: gom ảnh chủ nhân gửi (lô theo mtime) cho mục Lộc 12/10 + 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_1210'
os.makedirs(DICH, exist_ok=True)

ds = []
for p in glob.glob(os.path.join(CACHE, '*')):
    if os.path.isfile(p) and time.time() - os.path.getmtime(p) < 3600:
        ds.append((os.path.getmtime(p), p))
ds.sort()
print('  ảnh trong cache 60 phút qua: %d' % len(ds))
for t, p in ds[-6:]:
    print('   %s  %s  %d B' % (time.strftime('%H:%M:%S', time.localtime(t)), os.path.basename(p), os.path.getsize(p)))

# lấy LÔ: mọi ảnh trong cùng phút với ảnh mới nhất
if ds:
    tmax = ds[-1][0]
    lo = [(t, p) for t, p in ds if tmax - t < 120]
    print('  LÔ ảnh (cùng lượt, ±2 phút): %d' % len(lo))
    seen = {}
    n = 0
    for t, p in lo:
        h = hashlib.md5(open(p, 'rb').read()).hexdigest()[:12]
        if h in seen:
            print('   %s -> TRÙNG md5 với %s' % (os.path.basename(p), seen[h])); continue
        n += 1
        ten = 'loc_1210_%02d.jpg' % n
        shutil.copy2(p, os.path.join(DICH, ten))
        seen[h] = ten
        from PIL import Image
        im = Image.open(os.path.join(DICH, ten))
        print('   %s <- %s  %sx%s  %d B  md5 %s' % (ten, os.path.basename(p), im.width, im.height, os.path.getsize(os.path.join(DICH, ten)), h))
    print('  đã lưu %d ảnh vào %s' % (n, DICH))
