# -*- coding: utf-8 -*-
"""B34: (1) in nguyên văn các khối tin của Trí QC (tìm tin hôm nay) ;
(2) tải 3 ảnh của tin 18:56 bằng canvas->base64 (như pipeline KTV T41)."""
import base64, hashlib, json, os, re, subprocess, time

S = 'tri1010'
DICH = r'C:\Claw 2\QC\images\_tri_1010'
os.makedirs(DICH, exist_ok=True)
LOG = open(r'C:\Claw 2\QC\_log_zalo_tri_1010.txt', 'a', encoding='utf-8')


def log(*a):
    s = ' '.join(str(x) for x in a); print(s, flush=True); LOG.write(s + '\n'); LOG.flush()


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


def ev(js):
    return ba('--session', S, 'eval', js)


def ev_expr(expr):
    """ev nhưng ép trả về chuỗi (tránh mất dấu nháy kép) — dùng base64 khi cần"""
    return ba('--session', S, 'eval', expr)


j = json.load(open(r'C:\Claw 2\QC\_raw_zalo_tri_1010.json', encoding='utf-8'))
log('')
log('=== NGUYÊN VĂN CÁC KHỐI GẦN NHẤT ===')
for x in j['ds'][-8:]:
    log('--- #%s [%s] ảnh=%s file=%s' % (x['i'], 'ME' if re.search(r'\bme\b', x['cls']) else 'Tri', x['so_anh'], x['so_file']))
    log(repr(x['text'])[:1200])

# ── tải 3 ảnh của tin 18:56
IDS = ['1791633417771', '1791633417783', '1791633417791']
log('')
log('=== TẢI ẢNH (canvas -> base64) ===')
seen = {}
n = 0
for k, id_ in enumerate(IDS, 1):
    r = ev("(() => {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: '+e.message;} return 'OK '+g.naturalWidth+'x'+g.naturalHeight+' '+window.__B64.length;})()" % id_)
    log('  id %s: %s' % (id_, r[-40:]))
    if not r.startswith('OK'):
        continue
    tong = int(r.split()[-1])
    phan, vt = [], 0
    while vt < tong:
        x = ev("String(window.__B64.slice(%d,%d))" % (vt, vt + 30000)).strip()
        if x.startswith('"') and x.endswith('"'):
            x = x[1:-1]
        phan.append(x); vt += 30000
    chuoi = ''.join(phan)
    if len(chuoi) < tong * 0.9:
        log('     -> THIẾU dữ liệu (%d/%d) — bỏ' % (len(chuoi), tong)); continue
    raw = base64.b64decode(chuoi.split(',', 1)[1])
    n += 1
    p = os.path.join(DICH, 'tri_1010_%02d.jpg' % n)
    open(p, 'wb').write(raw)
    h = hashlib.md5(raw).hexdigest()[:12]
    if h in seen:
        log('     -> TRÙNG md5 với %s — xoá' % seen[h]); os.remove(p); n -= 1; continue
    seen[h] = os.path.basename(p)
    from PIL import Image
    im = Image.open(p)
    log('     -> %s  %d B  %sx%s  md5 %s' % (os.path.basename(p), len(raw), im.width, im.height, h))
log('đã tải %d ảnh vào %s' % (n, DICH))
LOG.close()
