# -*- coding: utf-8 -*-
r"""B154: mở Zalo Web bằng Chrome thật, xác nhận đăng nhập, mở hội thoại 'Trí QC'."""
import re, subprocess, time

S = 'qc1410'
def ba(*a, t=300):
    try:
        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()
    except Exception as e:
        return 'LOI: %s' % e

lst = ''
for _ in range(6):
    lst = ba('browser', 'list')
    if re.search(r'direct_local_\d+', lst):
        break
    time.sleep(4)
bid = (re.findall(r'(direct_local_\d+)', lst) or ['direct_local_123687895331504232'])[0]
print('  id:', bid)

ok = False
for lan in range(4):
    r = ba('--session', S, 'browser', 'open', bid, 'https://chat.zalo.me')
    if 'url=' in r or 'title=' in r:
        ok = True
        break
    print('  mở lần %d: %s' % (lan + 1, r[-70:].replace('\n', ' ')))
    time.sleep(8)
print('  mở Zalo:', 'OK' if ok else 'THẤT BẠI')
time.sleep(14)

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

print('  trạng thái:', ev("JSON.stringify({title:document.title, co_search:!!document.querySelector('#contact-search-input')})")[-140:])
# mở hội thoại Trí QC bằng DOM
print('  danh sách hội thoại:', ev("(()=>[...document.querySelectorAll('div[id^=friend-item-].conv-item')].slice(0,6).map(e=>e.innerText.split('\\n')[0]).join(' | '))()")[-200:])
print('  chọn Trí QC:', ev("""(()=>{const ds=[...document.querySelectorAll('div[id^=friend-item-].conv-item')];
  const t=ds.find(e=>/tr[iíy]\\s*qc/i.test(e.innerText)); if(!t) return 'KHÔNG THẤY';
  t.click(); return 'đã bấm: '+t.innerText.split('\\n')[0];})()""")[-60:])
time.sleep(6)
print('  tiêu đề hội thoại:', ev("(()=>{const h=document.querySelector('.header-title'); return h? h.innerText.trim() : '(không có)';})()")[-60:])
