# -*- coding: utf-8 -*-
r"""B126: chụp ảnh trang dashboard (đăng nhập) để gửi chủ nhân; đóng session Chrome."""
import os, re, subprocess, time

OUT = r'C:\Claw 2\Nghien cuu\Dashboard-CSDL\_anh_dashboard.png'
S = 'dashshot'

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()

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

lst = ''
for _ in range(4):
    lst = ba('browser', 'list')
    if re.search(r'direct_local_\d+', lst):
        break
    time.sleep(3)
bid = (re.findall(r'(direct_local_\d+)', lst) or ['direct_local_121304831500484624'])[0]
ba('--session', S, 'browser', 'open', bid, 'http://127.0.0.1:8097/')
time.sleep(7)
ev("(()=>{const i=document.querySelector('input[name=mat_khau]'); if(i){i.value='dash-bdd2bb'; i.closest('form').submit();} return 1;})()")
time.sleep(12)
ev("(()=>{const s=document.getElementById('sotuan'); if(s){s.value='T38';} const d=document.getElementById('den'); if(d){d.value='T41';} return 1;})()")
time.sleep(1)
ev("(()=>{const b=[...document.querySelectorAll('button')].find(x=>/Xem số liệu/.test(x.innerText)); if(b)b.click(); return 1;})()")
time.sleep(10)
print('  trạng thái:', ev("JSON.stringify({kpi:document.querySelectorAll('#kpis .kpi').length, ve:[...document.querySelectorAll('canvas')].filter(c=>Chart.getChart(c)).length})")[-120:])
print('  chụp:', ba('--session', S, 'screenshot', OUT, '--full')[-80:])
for s in ('dashtest', 'dashtest2', 'dashshot'):
    try:
        ba('session', 'close', s)
    except Exception:
        pass
print('  đã đóng session Chrome; ảnh tồn tại:', os.path.exists(OUT), os.path.getsize(OUT) if os.path.exists(OUT) else 0, 'byte')
