#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""线上（CDN）实测 P2 结构重构：新导航 + 融合页两态 + 订单 hub。"""
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 = []
    pg.on('pageerror', lambda e: errs.append(str(e)))
    pg.on('dialog', lambda d: d.accept())
    pg.goto(CDN, wait_until='load')
    pg.wait_for_timeout(3000)
    if '风险提醒' in pg.title():
        for sel in ['button:has-text("确定访问")', 'text=确定访问', 'button:has-text("继续")', 'button']:
            try:
                pg.click(sel, timeout=5000); pg.wait_for_timeout(3500); break
            except Exception:
                continue
    chk('CDN 页面已进入工作台', '销售工作台' in pg.title(), pg.title())
    if '销售工作台' not in pg.title():
        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(3200)
    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(1500)

    print('① 线上新导航')
    m = pg.evaluate("""() => ({ids:(window.TABS||[]).map(t=>t.id), groups:[...new Set((window.TABS||[]).map(t=>t.group))],
        nav:(document.getElementById('sidebar')||{}).innerText||'',
        bottom:(document.getElementById('bottomNav')||{}).innerText||''})""")
    chk('线上 Tab 数 = 14', len(m['ids']) == 14, str(len(m['ids'])))
    chk('线上四域', set(m['groups']) == {'biz', 'cust', 'mine', 'ai'}, str(m['groups']))
    chk('线上侧栏有「经营管理/客户管理」', '经营管理' in m['nav'] and '客户管理' in m['nav'])
    chk('线上侧栏无「我的活动/活动录入」', '我的活动' not in m['nav'] and '活动录入' not in m['nav'])
    chk('线上底栏含「拜访与活动」', '拜访与活动' in m['bottom'], m['bottom'].replace('\n', ' ')[:70])

    print('\n② 线上融合页')
    pg.evaluate("() => { visitHubState='see'; 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 {vals:[...document.querySelectorAll('#visitBody .value')].map(T), err:T(b).indexOf('加载失败')>=0,
              txt:T(b).slice(0,90)}; }""")
    chk('线上看态渲染 KPI、无加载失败', len(v['vals']) >= 2 and not v['err'], str(v['vals']) + ' ' + v['txt'][:50])
    pg.evaluate("() => visitSetState('rec')")
    pg.wait_for_timeout(3500)
    fr = None
    for f in pg.frames:
        if '活动录入.html' in (f.url or '') or '20261007p2' in (f.url or ''):
            fr = f
            break
    chk('线上录态 iframe 已挂载', fr is not None, (fr.url[:60] if fr else ''))
    if fr:
        has = fr.evaluate("() => ({ch:!!document.getElementById('channel'), card:!!document.getElementById('cardTodo')})")
        chk('线上录入页是新版（含活动形式/待办确认）', has['ch'] and has['card'], json.dumps(has))

    print('\n③ 线上订单 hub')
    pg.evaluate("() => { ordHubView='orders'; state.tab='orders'; render(); }")
    pg.wait_for_timeout(2500)
    o1 = pg.evaluate("() => { const b=document.getElementById('ordHubBody'); return b?b.innerHTML.length:0; }")
    pg.evaluate("() => { ordHubView='price'; render(); }")
    pg.wait_for_timeout(2500)
    o2 = pg.evaluate("() => { const b=document.getElementById('ordHubBody'); return b?b.innerHTML.length:0; }")
    chk('线上两视图都渲染且不同', o1 > 500 and o2 > 500 and o1 != o2, '%d / %d' % (o1, o2))

    chk('线下线上全程无 JS 错误', not errs, str(errs[:2]))
    pg.screenshot(path='/tmp/p2_live.png')
    br.close()

print('\n%s' % ('✅ 线上 P2 已生效' if ok else '❌ 线上有问题'))
sys.exit(0 if ok else 1)
