# -*- coding: utf-8 -*-
r"""B159: (1) xoá ảnh đã tải nhầm (của khối 13/10); (2) tải lại CHỈ ảnh thuộc HÔM NAY.
Lọc theo epoch trong id ảnh Zalo: img-<epoch_ms>-... > mốc 00:00 hôm nay.
Cách lấy: bấm từng thumbnail -> đọc #imageShowMainImage img -> canvas cap 1400 -> md5 khử trùng."""
import base64, hashlib, io, json, os, re, subprocess, time, datetime

S = 'qc1410'
RA = r'C:\Claw 2\QC\_qc1410'
ANH = r'C:\Claw 2\QC\images\_zalo_tri_1410'
LOG = os.path.join(RA, 'tien_do_anh.txt')


def ghi(t):
    with open(LOG, 'a', encoding='utf-8') as f:
        f.write('%s %s\n' % (time.strftime('%H:%M:%S'), t))
    print(t, flush=True)


def chay(args, inp=None, t=240):
    try:
        r = subprocess.run(['browser-act'] + args, input=inp, capture_output=True, text=True,
                           encoding='utf-8', errors='replace', timeout=t)
        return ((r.stdout or '') + (r.stderr or '')).strip()
    except Exception as e:
        return 'LOI: %s' % e


def ev(js, t=240):
    return chay(['--session', S, 'eval', '--stdin'], inp=js, t=t)


# 1) dọn ảnh tải nhầm
n = 0
for f in os.listdir(ANH):
    os.remove(os.path.join(ANH, f))
    n += 1
ghi('đã xoá %d ảnh tải nhầm (của khối 13/10)' % n)

moc = time.mktime(time.strptime('2026-10-14 00:00:00', '%Y-%m-%d %H:%M:%S')) * 1000
ghi('mốc hôm nay (epoch ms): %d' % moc)

# 2) đọc lại danh sách khối + chỉ lấy id ảnh >= mốc
d = ev(r"""(()=>{const ra={so_khoi:0, khoi:[]};
 const ks=[...document.querySelectorAll('.block-date')];
 ra.so_khoi=ks.length;
 ks.forEach((k,i)=>{
   const o={i:i, gio:(k.querySelector('.card-send-time__sendTime')||{}).innerText||'', tin:[]};
   [...k.querySelectorAll('.chat-message')].forEach(e=>{
     const t=(e.innerText||'').replace(/\s+/g,' ').trim();
     const ids=[...e.querySelectorAll('img.zimg-el')].filter(x=>(x.src||'').startsWith('blob:'))
               .map(x=>{const m=(x.id||'').match(/img-(\d+)/); return m? +m[1] : 0;}).filter(Boolean);
     if(t.length>0 || ids.length>0) o.tin.push({chu:/\bme\b/.test(e.className||''), dai:t.length, ids:ids, text:t.slice(0,1500)});
   });
   ra.khoi.push(o);
 });
 return JSON.stringify(ra);})()""", t=200)
j = json.loads(d)
with open(os.path.join(RA, 'zalo_all.json'), 'w', encoding='utf-8') as f:
    f.write(d)

can = []
for k in j['khoi']:
    for m in k['tin']:
        for eid in m['ids']:
            if eid >= moc:
                can.append((k['i'], k['gio'], m['text'][:60], eid))
ghi('ảnh thuộc HÔM NAY: %d' % len(can))
for x in can:
    ghi('  khối %d %s | id=%d | %s' % (x[0], x[1], x[3], x[2]))

JS_CAP = r"""(()=>{const im=document.querySelector('#imageShowMainImage img')||document.querySelector('img.zimage-viewer__img');
 if(!im) return 'CHUA_CO_ANH_LON';
 if(!im.naturalWidth) return 'ANH_CHUA_LOAD';
 const W=im.naturalWidth,H=im.naturalHeight,MAX=1400, sc=Math.min(1,MAX/Math.max(W,H));
 const c=document.createElement('canvas'); c.width=Math.round(W*sc); c.height=Math.round(H*sc);
 c.getContext('2d').drawImage(im,0,0,c.width,c.height);
 return JSON.stringify({w:W,h:H,tw:c.width,th:c.height,data:c.toDataURL('image/jpeg',0.92).split(',')[1]});})()"""

da = []
for (ki, gio, txt, eid) in can:
    thum = """(()=>{const t=[...document.querySelectorAll('img.zimg-el')].find(x=>x.id && x.id.indexOf('img-%d')>=0);
      if(!t) return 'KHONG_THAY_THUMB'; t.scrollIntoView({block:'center'}); t.dispatchEvent(new MouseEvent('click',{bubbles:true})); return 'da bam';})()""" % eid
    r = ev(thum, t=120)
    time.sleep(2.5)
    c = ''
    for lan in range(4):
        c = ev(JS_CAP, t=180)
        if c.startswith('{'):
            break
        time.sleep(2.5)
    if not c.startswith('{'):
        ghi('id=%d: %s (%s)' % (eid, c[:50], r[:30]))
        continue
    o = json.loads(c)
    raw = base64.b64decode(o['data'])
    md5 = hashlib.md5(raw).hexdigest()[:12]
    if md5 in [x[0] for x in da]:
        ghi('id=%d TRÙNG %s' % (eid, md5))
        continue
    ten = 'tri1410_%02d_%s.jpg' % (len(da) + 1, md5[:6])
    with open(os.path.join(ANH, ten), 'wb') as f:
        f.write(raw)
    da.append((md5, ten, o['w'], o['h'], len(raw)))
    ghi('ảnh %d: %s %dx%d (lưu %dx%d) %d byte | id=%d | %s' % (len(da), ten, o['w'], o['h'], o['tw'], o['th'], len(raw), eid, txt[:40]))

ev("(()=>{document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true})); return 1;})()", t=60)
ghi('XONG: %d ảnh HÔM NAY -> %s' % (len(da), ANH))
with open(os.path.join(RA, 'anh_da_tai.json'), 'w', encoding='utf-8') as f:
    json.dump([{'md5': m, 'ten': t, 'rong': w, 'cao': h, 'byte': b} for m, t, w, h, b in da], f, ensure_ascii=False, indent=1)
