# -*- coding: utf-8 -*-
r"""B152: chụp ảnh tab SẢN XUẤT (phần cạnh tranh) — có thử lại nhiều lần vì browser-act hay chập chờn."""
import os, re, subprocess, time

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

def ba(*a, t=300):
    try:
        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()
    except Exception as e:
        return 'LOI: %s' % e

# làm ấm + lấy id browser (thử nhiều lần)
bid = ''
for _ in range(8):
    lst = ba('browser', 'list')
    m = re.findall(r'(direct_local_\d+)', lst)
    if m:
        bid = m[0]
        break
    time.sleep(5)
print('  browser id:', bid or 'KHÔNG THẤY')
if not bid:
    raise SystemExit(1)

S = 'dashsx'
mo = False
for lan in range(5):
    r = ba('--session', S, 'browser', 'open', bid, 'http://127.0.0.1:8097/')
    if 'url=' in r or 'title=' in r:
        mo = True
        break
    print('  thử mở lần %d: %s' % (lan + 1, r[-60:].replace('\n', ' ')))
    time.sleep(6)
print('  mở trang:', 'OK' if mo else 'THẤT BẠI')
if not mo:
    raise SystemExit(2)

time.sleep(6)
def ev(js):
    return ba('--session', S, 'eval', js)
d = ev("!!document.querySelector('input[name=mat_khau]')").strip('"').lower()
if d == 'true':
    print('  đăng nhập:', ev("(()=>{const i=document.querySelector('input[name=mat_khau]'); i.value='btchem2026'; i.closest('form').submit(); return 'đã gửi';})()")[-20:])
    time.sleep(14)
ev("(()=>{window.__err=[];window.addEventListener('error',e=>window.__err.push(String(e.message)));return 1;})()")
print('  tab:', ev("(()=>{const t=[...document.querySelectorAll('.tab')].find(e=>e.dataset.k==='san_xuat'); if(t) t.click(); return 'đã chọn tab Sản xuất';})()")[-30:])
time.sleep(9)
print('  trạng thái:', ev("JSON.stringify({tab:(document.querySelector('.tab.on')||{}).textContent, kpi:document.querySelectorAll('#kpis .kpi').length, canvas:[...document.querySelectorAll('canvas')].filter(c=>Chart.getChart(c)).length+'/'+document.querySelectorAll('canvas').length, bang:document.querySelectorAll('#luoi table').length, loi:(window.__err||[]).length})")[-220:])
print('  chụp:', ba('--session', S, 'screenshot', os.path.join(GOC, '_anh_san_xuat.png'), '--full')[-46:])
ba('session', 'close', S)
p = os.path.join(GOC, '_anh_san_xuat.png')
print('  ảnh:', os.path.getsize(p) if os.path.exists(p) else 'KHÔNG CÓ', 'byte')
