# -*- coding: utf-8 -*-
r"""B57: tải nốt ảnh các khối #0,#3,#4 của Zalo Lộc 12/10 -> gộp TẤT CẢ ảnh (khử trùng md5) vào _agy_loc_1210."""
import base64, hashlib, json, os, re, shutil, subprocess, time

S = 'loc1210'
Z = r'C:\Claw 2\QC\images\_zalo_loc_1210'
DICH = r'C:\Claw 2\QC\images\_agy_loc_1210'
os.makedirs(DICH, exist_ok=True)
j = json.load(open(r'C:\Claw 2\QC\_raw_zalo_loc_1210.json', encoding='utf-8'))


def ba(*a, timeout=200):
    r = subprocess.run(['browser-act'] + list(a), capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout)
    return ((r.stdout or '') + (r.stderr or '')).strip()


# mở lại browser + vào đúng hội thoại (đã đóng ở bước trước)
lst = ba('browser', 'list')
ID = re.search(r'id=(direct_local_\d+)', lst).group(1)
ba('--session', S, 'browser', 'open', ID, 'https://chat.zalo.me')
time.sleep(15)
ba('--session', S, 'eval', "(() => {const s=document.querySelector('#contact-search-input'); if(!s) return 'x'; s.focus(); document.execCommand('selectAll',false,null); document.execCommand('insertText',false,'Loc QC'); return 'ok';})()")
time.sleep(4)
ba('--session', S, 'eval', "(()=>{const d=document.querySelector('div[id^=friend-item-].conv-item')||document.querySelector('div[id^=friend-item-]'); if(!d) return 'x'; d.click(); return 'ok';})()")
time.sleep(5)
for i in range(4):
    ba('--session', S, 'eval', "(()=>{const c=[...document.querySelectorAll('div,section,ul')].filter(e=>e.scrollHeight>e.clientHeight+200); c.sort((a,b)=>b.scrollHeight-a.scrollHeight); if(c[0]){c[0].scrollTop=c[0].scrollTop-1500;} return 1;})()")
    time.sleep(2)
print('  header:', ba('--session', S, 'eval', "(document.querySelector('.header-title')||{}).innerText||'?'")[-60:])

n = len([f for f in os.listdir(Z) if f.endswith('.jpg')])
for blk in (0, 3, 4):
    x = [y for y in j['ds'] if y['i'] == blk]
    if not x:
        print('  khối #%s không có trong raw' % blk); continue
    x = x[0]
    print('=== khối #%s: %d ảnh' % (blk, x['so_anh']))
    for a in x['anh']:
        id_ = a['id'].split('.')[0].replace('img-', '')
        r = ba('--session', S, 'eval', "(() => {const l=[...document.querySelectorAll('img.zimg-el')]; const g=l.find(x=>(x.id||'').indexOf('%s')>=0); if(!g) return 'KHONG THAY'; g.scrollIntoView({block:'center'}); if(!g.naturalWidth) return 'CHUA LOAD'; const c=document.createElement('canvas'); c.width=g.naturalWidth; c.height=g.naturalHeight; c.getContext('2d').drawImage(g,0,0,c.width,c.height); try{window.__B64=c.toDataURL('image/jpeg',0.92);}catch(e){return 'LOI';} return 'OK '+g.naturalWidth+'x'+g.naturalHeight+' '+window.__B64.length;})()" % id_)
        if not r.startswith('OK'):
            print('   id %s: %s' % (id_, r[-30:])); continue
        tong = int(r.split()[-1]); phan, vt = [], 0
        while vt < tong:
            z = ba('--session', S, 'eval', 'String(window.__B64.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:
            print('   id %s: THIẾU dữ liệu' % id_); continue
        th = base64.b64decode(chuoi.split(',', 1)[1])
        n += 1
        open(os.path.join(Z, 'zalo_loc_1210_%02d.jpg' % n), 'wb').write(th)
        print('   -> zalo_loc_1210_%02d.jpg  %d B  %s' % (n, len(th), r.split()[1]))
ba('session', 'close', S)
print('  đã đóng browser')

# ── gộp tất cả ảnh (khử trùng md5) vào thư mục cho AGY
print()
print('  === GỘP cho AGY (khử trùng md5) ===')
seen, k = {}, 0
for d in (r'C:\Claw 2\QC\images\_loc_1210', Z):
    for f in sorted(os.listdir(d)):
        p = os.path.join(d, f)
        if not os.path.isfile(p):
            continue
        h = hashlib.md5(open(p, 'rb').read()).hexdigest()[:12]
        if h in seen:
            print('   %-24s TRÙNG với %s' % (f[:24], seen[h])); continue
        k += 1
        ten = 'anh_%02d_%s.jpg' % (k, os.path.splitext(f)[0][:22])
        shutil.copy2(p, os.path.join(DICH, ten))
        seen[h] = ten
        from PIL import Image
        im = Image.open(os.path.join(DICH, ten))
        print('   %-46s %sx%s  %d B  md5 %s' % (ten, im.width, im.height, os.path.getsize(os.path.join(DICH, ten)), h))
print('  TỔNG %d ảnh trong %s' % (k, DICH))
