# -*- coding: utf-8 -*-
r"""B96: lấy BẢN GỐC ảnh nhóm Zalo (viewer 768x1024 / 1920x2560) — mở viewer 1 thumbnail rồi điều hướng
bằng phím ArrowRight, mỗi lượt gom mọi ảnh lớn có trong DOM (md5 khử trùng)."""
import base64, hashlib, os, re, subprocess, time

S = 'tri1310'
DICH = r'C:\Claw 2\QC\images\_zalo_tri_1310_full'
os.makedirs(DICH, exist_ok=True)
LOG = open(r'C:\Claw 2\QC\_log_zalo_tri_1310_full.txt', 'a', encoding='utf-8')
log = lambda *a: (print(*a, flush=True), LOG.write(' '.join(str(x) for x in a) + '\n'), LOG.flush())


def ev(js, t=240):
    r = subprocess.run(['browser-act', '--session', S, 'eval', js], capture_output=True, text=True,
                       encoding='utf-8', errors='replace', timeout=t)
    return ((r.stdout or '') + (r.stderr or '')).strip()


MOC = 1400  # cạnh dài tối đa khi chụp lại (giữ đủ nét chữ trên phiếu)
JS_LIST = """(() => {
  const ds=[...document.querySelectorAll('img.zimg-el')].filter(x=>x.naturalWidth>=400).map((x,i)=>({i:i,key:x.naturalWidth+'x'+x.naturalHeight+'#'+(x.src||'').slice(-18)}));
  return JSON.stringify({n:ds.length, ds:ds});
})()"""
JS_GRAB = """(() => {const g=%d; const l=[...document.querySelectorAll('img.zimg-el')].filter(x=>x.naturalWidth>=400); const x=l[g]; if(!x) return 'KHONG THAY';
 const k=%d/x.naturalWidth; const w=Math.round(x.naturalWidth*k), h=Math.round(x.naturalHeight*k);
 const c=document.createElement('canvas'); c.width=w; c.height=h; c.getContext('2d').drawImage(x,0,0,w,h);
 try{window.__B=c.toDataURL('image/jpeg',0.9);}catch(e){return 'LOI';} return 'OK '+w+'x'+h+' '+window.__B.length;})()"""

seen, n = {}, 0
for luot in range(26):
    ds = ev(JS_LIST)
    try:
        j = re.sub(r'^"|"$', '', ds)
        arr = re.findall(r'\{"i":(\d+),"key":"([^"]+)"\}', j.replace('\\"', '"'))
    except Exception:
        arr = []
    moi = 0
    for i_s, key in arr:
        i = int(i_s)
        r = ev(JS_GRAB % (i, MOC))
        if not r.startswith('OK'):
            continue
        w, h, tong = r.split()[1], r.split()[2], int(r.split()[-1])
        phan, vt = [], 0
        while vt < tong:
            z = ev('String(window.__B.slice(%d,%d))' % (vt, vt + 30000)).strip()
            if z.startswith('"') and z.endswith('"'):
                z = z[1:-1]
            phan.append(z); vt += 30000
        chuoi = ''.join(phan)
        if len(chuoi) < tong * 0.9:
            log('   bỏ 1 ảnh (thiếu dữ liệu)'); continue
        th = base64.b64decode(chuoi.split(',', 1)[1])
        md5 = hashlib.md5(th).hexdigest()[:12]
        if md5 in seen:
            continue
        n += 1
        ten = os.path.join(DICH, 'goc_%02d.jpg' % n)
        open(ten, 'wb').write(th)
        seen[md5] = os.path.basename(ten)
        moi += 1
        log('   %-16s %8d B  %s  md5 %s' % (os.path.basename(ten), len(th), w + 'x' + h, md5))
    log('  lượt %d: DOM có %d ảnh lớn | mới %d | tổng %d' % (luot, len(arr), moi, n))
    if n >= 15:
        break
    if n == 0 and luot == 0:
        log('  mở viewer:')
        log('   ' + ev("(()=>{const g=[...document.querySelectorAll('img.zimg-el')][0]; const c=g.closest('.img-center-box')||g.parentElement; (c||g).click(); return 'clicked';})()")[-60:])
        time.sleep(4)
        continue
    ev("(()=>{document.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowRight',keyCode:39,which:39,bubbles:true})); const b=document.body; b.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowRight',keyCode:39,which:39,bubbles:true})); return 1;})()")
    time.sleep(2.5)

log('  === TỔNG %d ảnh gốc trong %s' % (n, DICH))
LOG.close()
