# -*- coding: utf-8 -*-
r"""B134: kiểm việc TỰ CHUẨN HOÁ địa chỉ khi mở link thiếu dấu / — điều hướng bằng JS (tránh timeout của browser open)."""
import re, subprocess, time

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 = 'dashv2'
print('  browser:', bid)
print('  mở trang gốc trước:', ba('--session', S, 'browser', 'open', bid, 'http://127.0.0.1:8097/')[-40:])
time.sleep(8)

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

print('  đang ở:', ev("location.pathname").strip('"'))

# 1) Điều hướng bằng JS tới link THIẾU dấu / (đúng ca anh gặp)
ev("(()=>{location.href='https://desktop-9gsdkd2.tail0ffe94.ts.net/dashboard'; return 1;})()")
time.sleep(14)
print('  sau khi vào link thiếu /:')
print('    địa chỉ   :', ev("location.pathname").strip('"'))
print('    tiêu đề   :', ev("document.title").strip('"')[-40:])
print('    KPI       :', ev("document.querySelectorAll('#kpis .kpi').length").strip('"'))
print('    biểu đồ vẽ:', ev("(()=>{try{[...document.querySelectorAll('canvas')].filter(c=>Chart.getChart(c)).length; return [...document.querySelectorAll('canvas')].filter(c=>Chart.getChart(c)).length + '/' + document.querySelectorAll('canvas').length;}catch(e){return 'LOI: '+e.message;}})()").strip('"'))
print('    chart.js có:', ev("typeof Chart").strip('"'))
ba('session', 'close', S)
