# -*- coding: utf-8 -*-
r"""B102: mở lại Zalo -> hội thoại 'Trí QC' -> click 1 thumbnail album hôm nay -> DÒ selector ảnh đang hiển thị
(#imageShowMainImage img) để lần sau chỉ lấy ĐÚNG ảnh của album hôm nay (tránh viewer nhớ album cũ)."""
import re, subprocess, time

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

lst = ba('browser', 'list')
m = re.findall(r'(direct_local_\d+)', lst)
print('  browser id:', m[0] if m else 'KHÔNG THẤY')
if not m:
    raise SystemExit(1)
print('  mở:', ba('--session', S, 'browser', 'open', m[0], 'https://chat.zalo.me')[-80:])
time.sleep(16)
print('  trạng thái:', ev("JSON.stringify({t:document.title, co:!!document.querySelector('#contact-search-input')})")[-100:])
ev("(() => {const s=document.querySelector('#contact-search-input'); if(!s) return 'x'; s.focus(); document.execCommand('selectAll',false,null); document.execCommand('insertText',false,'Trí QC'); return 'ok';})()")
time.sleep(4)
print('  mở hội thoại:', ev("(()=>{const d=document.querySelector('div[id^=friend-item-].conv-item')||document.querySelector('div[id^=friend-item-]'); if(!d) return 'khong thay'; d.click(); return 'da mo';})()")[-30:])
time.sleep(5)
for i in range(6):
    ev("(()=>{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('  album hôm nay:', ev("(()=>{const t=[...document.querySelectorAll('img.zimg-el')].filter(x=>x.naturalWidth<400 && /--group-item/.test((x.parentElement.className||''))); return String(t.length);})()")[-20:])
print('  click thumb 0:', ev("(()=>{const t=[...document.querySelectorAll('img.zimg-el')].filter(x=>x.naturalWidth<400 && /--group-item/.test((x.parentElement.className||''))); const g=t[0]; if(!g) return 'khong thay'; g.scrollIntoView({block:'center'}); (g.closest('.img-center-box')||g.parentElement).click(); return 'ok';})()")[-20:])
time.sleep(4)
print('  #imageShowMainImage:', ev("(()=>{const i=document.querySelector('#imageShowMainImage img'); return i? JSON.stringify({nw:i.naturalWidth, nh:i.naturalHeight, cls:i.className}) : 'KHONG CO';})()")[-120:])
print('  media-viewer imgs:', ev("(()=>{const v=document.querySelector('.media-viewer'); if(!v) return 'khong co viewer'; const l=[...v.querySelectorAll('img')].map(x=>x.naturalWidth+'x'+x.naturalHeight+((x.className||'').length?'/'+x.className.slice(0,24):'')); return JSON.stringify(l.slice(0,8));})()")[-260:])
