# -*- coding: utf-8 -*-
r"""B145: thử lại tab BÁN HÀNG — click rồi CHỜ đúng nội dung, chụp ảnh."""
import os, re, subprocess, time

GOC = r'C:\Claw 2\Nghien cuu\Dashboard-CSDL'

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

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_121304831500484624'])[0]
S = 'dashbh2'
ok = False
for lan in range(4):
    r = ba('--session', S, 'browser', 'open', bid, 'http://127.0.0.1:8097/')
    if 'title=' in r or 'url=' in r:
        ok = True
        break
    time.sleep(5)
print('  mở trang:', 'OK' if ok else 'THẤT BẠI')
time.sleep(9)
def ev(js):
    return ba('--session', S, 'eval', js)
if ev("!!document.querySelector('input[name=mat_khau]')").strip('"').lower() == 'true':
    ev("(()=>{const i=document.querySelector('input[name=mat_khau]'); i.value='btchem2026'; i.closest('form').submit(); return 1;})()")
    time.sleep(13)
ev("(()=>{window.__err=[];window.addEventListener('error',e=>window.__err.push(String(e.message)));return 1;})()")
print('  tab đang mở:', ev("(document.querySelector('.tab.on')||{}).textContent").strip('"'))
# click đúng thẻ tab Bán hàng
print('  click:', ev("(()=>{const t=[...document.querySelectorAll('.tab')].find(e=>e.textContent.trim()==='Bán hàng'); if(!t) return 'không thấy tab'; t.click(); return 'đã click';})()")[-40:].strip('"'))
for i in range(10):
    time.sleep(2)
    k1 = ev("(document.querySelector('#kpis .kpi .n')||{}).textContent").strip('"')
    if k1 == '347.102':
        break
print('  tab đang mở:', ev("(document.querySelector('.tab.on')||{}).textContent").strip('"'), '| KPI đầu:', k1)
print('  bảng số:', ev("[...document.querySelectorAll('#kpis .kpi')].map(e=>e.innerText.replace(/\\n/g,' = ')).join(' | ')")[-340:])
print('  thẻ:', ev("[...document.querySelectorAll('#luoi h3')].map(e=>e.textContent).join(' · ')")[-300:])
print('  canvas vẽ:', ev("[...document.querySelectorAll('canvas')].filter(c=>Chart.getChart(c)).length").strip('"'), '/',
      ev("document.querySelectorAll('canvas').length").strip('"'), '| bảng:', ev("document.querySelectorAll('#luoi table').length").strip('"'),
      '| dòng:', ev("document.querySelectorAll('#luoi table tbody tr').length").strip('"'))
print('  nguồn:', ev("document.getElementById('nguon').textContent")[-120:].strip('"'))
print('  lỗi JS:', ev("JSON.stringify((window.__err||[]).slice(0,3))")[-100:])
print('  chụp:', ba('--session', S, 'screenshot', os.path.join(GOC, '_anh_ban_hang.png'), '--full')[-40:])
ba('session', 'close', S)
p = os.path.join(GOC, '_anh_ban_hang.png')
print('  ảnh:', os.path.getsize(p) if os.path.exists(p) else 'KHÔNG CÓ', 'byte')
