#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""真实用户路径实测：在 **CDN 地址**上打开工作台，切到拜访视图，验证不再出现 JSON 解析失败。

覆盖：CDN 静态页 → AUTH_APIS 绝对基址 → 隧道 API（含跨域）→ 渲染 KPI。
"""
import json
import sys
from playwright.sync_api import sync_playwright

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
CDN = 'https://bier-sales-d0gatbvlx288724e9-1458438710.tcloudbaseapp.com/workbench/index.html'
USER = '刘新元'
sess = json.load(open(ROOT + '/数据/auth_sessions.json', encoding='utf-8'))
mine = sorted([(v['expire_at'], k, v) for k, v in sess.items() if v.get('name') == USER], reverse=True, key=lambda x: x[0])
TOKEN, IDENT = mine[0][1], dict(mine[0][2])
IDENT['open_id'] = 'ou_preview_only'
IDENT.pop('expire_at', None)

ok = True
def chk(label, cond, detail=''):
    global ok
    print('  %s %-40s %s' % ('✅' if cond else '❌', label, detail))
    if not cond:
        ok = False

with sync_playwright() as p:
    br = p.chromium.launch(channel='chrome', headless=True)
    pg = br.new_page(viewport={'width': 1500, 'height': 1000})
    errs, reqs = [], []
    pg.on('pageerror', lambda e: errs.append(str(e)))
    pg.on('request', lambda r: reqs.append(r.url) if '/api/' in r.url or '/workbench/' in r.url else None)
    pg.on('dialog', lambda d: d.accept())

    pg.goto(CDN, wait_until='load')
    pg.wait_for_timeout(3000)
    # CloudBase 测试域名会先弹「风险提醒」中间页（真实用户要手动点「确定访问」）
    if '风险提醒' in pg.title():
        print('  · 命中 CloudBase 风险提醒中间页，尝试点击「确定访问」…')
        for sel in ['button:has-text("确定访问")', 'text=确定访问', 'a:has-text("确定访问")',
                    'button:has-text("继续")', 'button']:
            try:
                pg.click(sel, timeout=5000)
                pg.wait_for_timeout(3500)
                break
            except Exception:
                continue
        print('  · 点击后标题：%r' % pg.title())
    t = pg.title()
    chk('CDN 页面已打开（非飞书授权页）', '销售工作台' in t, t)
    if not pg.evaluate("() => typeof window.render === 'function'"):
        print('  ⚠ 页面未进入工作台（仍停在 %r），后续断言无法进行' % t)
        br.close()
        sys.exit(1)

    pg.evaluate("""([tk, idn]) => {
        localStorage.setItem('bior_auth_token', tk);
        localStorage.setItem('bior_sw_user_v2', JSON.stringify(idn));
    }""", [TOKEN, IDENT])
    pg.reload(wait_until='load')
    pg.wait_for_timeout(3000)
    pg.evaluate("""() => { window.state = window.state || {};
        window.state.user = JSON.parse(JSON.stringify(%s));
        if (typeof showApp === 'function') showApp(); }""" % json.dumps(IDENT, ensure_ascii=False))
    pg.wait_for_timeout(1200)

    chk('线上页面含 visitStats Tab', pg.evaluate("() => (window.TABS||[]).some(t => t.id === 'visitStats')"))
    chk('线上已有 wbReq 基址解析', pg.evaluate("() => typeof window.wbReq === 'function'"))

    reqs.clear()
    pg.evaluate("() => { state.tab='visitStats'; render(); }")
    pg.wait_for_timeout(4000)
    v = pg.evaluate("""() => {
      const b = document.getElementById('visitBody');
      const T = e => (e ? e.innerText.replace(/\\s+/g,' ').trim() : '');
      return {body: T(b).slice(0, 200),
              vals: [...document.querySelectorAll('#visitBody .value')].map(T),
              hasErr: T(b).indexOf('加载失败') >= 0 || T(b).indexOf('Unexpected token') >= 0};
    }""")
    chk('无「加载失败 / JSON 解析」提示', not v['hasErr'], v['body'][:80])
    chk('渲染出 KPI 数字', len(v['vals']) >= 2, str(v['vals']))
    api = [u for u in reqs if 'api' in u]
    chk('接口走绝对基址（非 CDN 相对路径）',
        all(('tcloudbaseapp.com' not in u) for u in api) and any('biorisales.site' in u for u in api),
        str(api[:2]))
    chk('无 JS 错误', not errs, str(errs[:2]))
    pg.screenshot(path='/tmp/visit_live.png')
    br.close()

print('\n%s' % ('✅ CDN 真实路径上拜访视图已正常' if ok else '❌ 仍存在问题'))
sys.exit(0 if ok else 1)
