# -*- coding: utf-8 -*-
r"""B125: thử trang dashboard qua LINK TAILSCALE (đúng link anh dùng trên điện thoại) — đăng nhập + biểu đồ."""
import re, subprocess, sys, time

URL = 'https://desktop-9gsdkd2.tail0ffe94.ts.net/dashboard/'
S = 'dashfun'

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]
print('  mở:', ba('--session', S, 'browser', 'open', bid, URL)[-60:])
time.sleep(8)
print('  trang đăng nhập:', ev("JSON.stringify({title:document.title, co_pass:!!document.querySelector('input[name=mat_khau]'), base:(document.querySelector('base')||{}).href})")[-220:])
ev("(()=>{const i=document.querySelector('input[name=mat_khau]'); if(i){i.value='dash-bdd2bb'; i.closest('form').submit();} return 1;})()")
time.sleep(12)
print('  sau đăng nhập  :', ev("JSON.stringify({title:document.title, co_pass:!!document.querySelector('input[name=mat_khau]'), kpi:document.querySelectorAll('#kpis .kpi').length})")[-200:])
print('  biểu đồ        :', ev("(()=>{const cs=[...document.querySelectorAll('canvas')]; const ve=cs.filter(c=>Chart.getChart(c)).length; const c=Chart.getChart('c_cont'); return JSON.stringify({canvas:cs.length, da_ve:ve, tuan:(c?c.data.labels.length:0), cont_t41:(c?c.data.datasets[0].data[c.data.labels.length-1]:null)});})()")[-220:])
print('  KPI (3 thẻ đầu):', ev("(()=>[...document.querySelectorAll('#kpis .kpi')].slice(0,3).map(e=>e.innerText.replace(/\\n/g,' = ')).join(' | '))()")[-200:])
print('  nhịp CSDL      :', ev("(document.getElementById('nhip')||{}).textContent")[-60:])
ba('session', 'close', S)
