# -*- coding: utf-8 -*-
r"""B157: TỰ ĐỘNG chờ quyền Chrome -> mở Zalo -> mở hội thoại 'Trí QC' -> lưu nguyên văn tin nhắn HÔM NAY.
Chạy nền vài phút: mỗi lượt thử lại cách nhau 15 giây, để chủ nhân bấm Allow lúc nào cũng vào việc được."""
import base64, json, os, re, subprocess, sys, time

ID = 'direct_local_123687895331504232'
S = 'qc1410'
RA = r'C:\Claw 2\QC\_qc1410'
os.makedirs(RA, exist_ok=True)
LOG = os.path.join(RA, 'tien_do.txt')


def ghi(t):
    with open(LOG, 'a', encoding='utf-8') as f:
        f.write('%s %s\n' % (time.strftime('%H:%M:%S'), t))
    print(t, flush=True)


def ba(*a, t=200):
    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


def ev(js):
    """Chạy JS qua stdin (base64) để không bị ăn dấu nháy."""
    b64 = base64.b64encode(js.encode('utf-8')).decode()
    return ba('--session', S, 'eval', '--stdin', t=200) if False else \
chay_stdin(b64)


def chay_stdin(b64):
    try:
        r = subprocess.run(['browser-act', '--session', S, 'eval', '--stdin'],
                           input=base64.b64decode(b64).decode('utf-8'),
                           capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=200)
        return ((r.stdout or '') + (r.stderr or '')).strip()
    except Exception as e:
        return 'LOI: %s' % e


# ─── 1) chờ quyền: thử mở nhiều lần ───
mo = False
for lan in range(14):
    r = ba('--session', S, 'browser', 'open', ID, 'https://chat.zalo.me', t=120)
    if 'url=' in r or 'title=' in r:
        mo = True
        ghi('MỞ ZALO OK ở lần %d' % (lan + 1))
        break
    ghi('lần %d: %s' % (lan + 1, r[-60:].replace('\n', ' ')))
    time.sleep(15)
if not mo:
    ghi('KHÔNG mở được — hết lượt thử')
    sys.exit(1)

time.sleep(15)
tt = ev("JSON.stringify({title:document.title, co_search:!!document.querySelector('#contact-search-input')})")
ghi('trạng thái: ' + tt[-160:])

# ─── 2) mở hội thoại Trí QC ───
js_search = """(()=>{const s=document.querySelector('#contact-search-input');
 if(!s) return 'KHONG CO O TIM';
 s.focus(); document.execCommand('selectAll',false,null);
 document.execCommand('insertText',false,'Tri QC'); return 'da go tu khoa';})()"""
ghi('tìm: ' + ev(js_search)[-60:])
time.sleep(5)
js_click = """(()=>{const ds=[...document.querySelectorAll('div[id^=friend-item-].conv-item')];
 const t=ds.find(e=>/tr[iíy]\\s*qc/i.test(e.innerText));
 return JSON.stringify({so_dong:ds.length, ten:ds.slice(0,4).map(e=>e.innerText.split('\\n')[0]),
   bam:t? t.innerText.split('\\n')[0] : 'KHONG THAY'});})()"""
ghi('kết quả tìm: ' + ev(js_click)[-220:])
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) t.click(); return 1;})()""")
time.sleep(7)
htar = ev("(()=>{const h=document.querySelector('.header-title'); return h? h.innerText.trim() : '(khong co)';})()")
ghi('tiêu đề hội thoại: ' + htar[-60:])

# ─── 3) cuộn lên xuống cho nạp đủ, rồi dump khối tin ───
js_dump = r"""(()=>{
 const ra={};
 const khoi=[...document.querySelectorAll('.block-date')];
 ra.so_khoi=khoi.length;
 const cuoi=khoi[khoi.length-1];
 if(!cuoi) return JSON.stringify(ra);
 ra.gio_khoi=(cuoi.querySelector('.card-send-time__sendTime')||{}).innerText||'';
 const tin=[...cuoi.querySelectorAll('.chat-message')];
 ra.so_tin=tin.length;
 ra.tin=tin.map(e=>{
   const cls=e.className||'';
   const anh=[...e.querySelectorAll('img.zimg-el')].filter(i=>(i.src||'').startsWith('blob:')).length;
   const av=[...e.querySelectorAll('img')].length;
   const t=(e.innerText||'').replace(/\s+/g,' ').trim();
   return {cua_chu_nhan:/\bme\b/.test(cls.split(' ').join(' ')), dai:t.length,
           so_anh:anh, so_img:av, text:t.slice(0,1200)};
 }).filter(x=>x.dai>0 || x.so_anh>0);
 return JSON.stringify(ra);
})()"""
d = ev(js_dump)
with open(os.path.join(RA, 'zalo_raw.json'), 'w', encoding='utf-8') as f:
    f.write(d)
ghi('dump: %d ký tự -> zalo_raw.json' % len(d))
ghi('tóm tắt: ' + d[:400])
