#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""线上（CDN）验收 LS 课题组 Tab。含腾讯云「风险提醒」拦截页绕过。"""
import io
import json
import sys

from playwright.sync_api import sync_playwright

CDN = 'https://bier-sales-d0gatbvlx288724e9-1458438710.tcloudbaseapp.com/workbench/index.html'
GT = json.load(io.open('/Users/liuxinyuan/Desktop/Hermes输出-工作类/数据/ls_groups.json', encoding='utf-8'))
OK = True


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


def passwall(pg, tries=4):
    for _ in range(tries):
        if '风险提醒' not in pg.title() and '拦截' not in pg.title():
            return True
        try:
            pg.click('text=确定访问', timeout=3000)
        except Exception:
            try:
                pg.click('text=继续访问', timeout=2000)
            except Exception:
                pass
        pg.wait_for_timeout(1500)
    return '风险提醒' not in pg.title()


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.goto(CDN, wait_until='load')
    pg.wait_for_timeout(1200)
    t = pg.title()
    print('  首屏 title = %r' % t)
    if '风险提醒' in t or '拦截' in t:
        ok = passwall(pg)
        chk('绕过风险提醒页', ok, 'title=%r' % pg.title())
    chk('拿到真页面（非拦截页）', '风险提醒' not in pg.title(), pg.title())
    chk('页面已渲染 workbench', pg.evaluate("() => typeof state !== 'undefined' && typeof render === 'function'"))

    pg.evaluate("""async () => {
        document.getElementById('loginOverlay').style.display='none';
        document.getElementById('app').style.display='block';
        state.user = {name:'刘新元', role:'admin', dept:'销售管理', line:'both'};
        state.currentLine = 'ls';
        var d = await fetch('../数据/ls_groups.json?v='+Date.now(), {cache:'no-store'}).then(r=>r.json());
        state.data = state.data || {};
        state.data.lsGroups = d;
        state.tab = 'groups'; render();
    }""")
    pg.wait_for_timeout(1500)

    cards = pg.evaluate("() => [...document.querySelectorAll('.stats-grid')].map(g=>[...g.children].map(c=>"
                        "c.querySelector('.value').innerText.trim()+'|'+c.querySelector('.label').innerText.trim()))")
    flat = {r.split('|')[1]: r.split('|')[0] for row in cards for r in row}
    print('  线上 KPI：', cards)
    chk('KPI 两排 8 张', sum(len(r) for r in cards) == 8)
    chk('有采购记录 = %d' % GT['paids'], flat.get('💰 有采购记录') == str(GT['paids']))
    chk('累计成交额 = %.2f万' % (GT['amount_total'] / 1e4), flat.get('💵 累计成交额', '').startswith('%.2f' % (GT['amount_total'] / 1e4)))
    chk('成交货号 = %d' % GT['skus_total'], flat.get('🧾 成交货号') == str(GT['skus_total']))
    chk('覆盖客户 = %d' % GT['customers_total'], flat.get('🏢 覆盖客户') == str(GT['customers_total']))

    rows = pg.evaluate("() => document.querySelectorAll('.data-table tbody tr').length")
    chk('线上行数 = %d' % len(GT['groups']), rows == len(GT['groups']), str(rows))
    body = pg.evaluate("() => document.querySelector('.data-table tbody').innerText")
    chk('线上含「归并」标记', '归并' in body)
    chk('线上 TOP1 = 戴春艳课题组 ¥32,664', '戴春艳课题组' in body.split('\n')[0] and '¥32,664' in body)
    chk('线上标注口径（Q1=B）', '标准销售订单' in pg.evaluate("() => document.querySelector('main').innerText"))
    chk('0 JS 错误', len(errs) == 0, str(errs[:2]))
    pg.screenshot(path='/tmp/ls_groups_live.png', full_page=False)
    br.close()

print('\n%s' % ('✅ 线上全部通过' if OK else '❌ 有失败项'))
sys.exit(0 if OK else 1)
