# -*- coding: utf-8 -*-
r"""B129: thử đăng nhập 3 đường bằng Chrome thật với MẬT KHẨU MỚI btchem2026.
(a) funnel thiếu dấu / (b) funnel đủ dấu / (c) nội bộ 127.0.0.1."""
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(5):
    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('  browser:', bid)

DUONG = [
    ('a) funnel THIẾU dấu /', 'https://desktop-9gsdkd2.tail0ffe94.ts.net/dashboard'),
    ('b) funnel ĐỦ dấu /', 'https://desktop-9gsdkd2.tail0ffe94.ts.net/dashboard/'),
    ('c) nội bộ 127.0.0.1', 'http://127.0.0.1:8097/'),
]
S = None
for ten, url in DUONG:
    S = 'dash_' + re.sub(r'\W', '', ten.split(')')[0])
    ba('--session', S, 'browser', 'open', bid, url)
    time.sleep(8)
    def ev(js):
        return ba('--session', S, 'eval', js)
    ev("(()=>{window.__err=[];window.addEventListener('error',e=>window.__err.push(String(e.message)));return 1;})()")
    dia = ev("location.href").strip('"')[-70:]
    co_o = ev("!!document.querySelector('input[name=mat_khau]')").strip('"')
    act = ev("(()=>{const f=document.querySelector('form'); return f? f.getAttribute('action') : '(không có form)';})()").strip('"')
    print('\n  %s  →  %s' % (ten, url))
    print('    địa chỉ sau khi mở :', dia)
    print('    có ô mật khẩu      :', co_o, '| form action:', act)
    if co_o.lower() == "true":
        ev("(()=>{const i=document.querySelector('input[name=mat_khau]'); i.value='btchem2026'; i.closest('form').submit(); return 1;})()")
        time.sleep(11)
        print('    SAU ĐĂNG NHẬP      :', ev("JSON.stringify({dia:location.pathname, tieu_de:document.title, kpi:document.querySelectorAll('#kpis .kpi').length, ve:[...document.querySelectorAll('canvas')].filter(c=>Chart.getChart(c)).length, loi:(window.__err||[]).slice(0,2)})")[-230:])
    else:
        print('    (đã đăng nhập sẵn, không hiện ô mật khẩu) — KPI:', ev("document.querySelectorAll('#kpis .kpi').length").strip('"'))
    ba('session', 'close', S)
