#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""《宝锐销售助手 · 使用手册》验收：渲染 / 零外链 / 零报错 / 品牌 DOM / 敏感串 / 手机版长图。"""
import os
import re
import sys

from playwright.sync_api import sync_playwright

HTML = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/团队共享/宝锐销售助手_使用手册.html'
SHOT = os.path.expanduser('~/.hermes/profiles/zone-b/cache/scratch/manual')
os.makedirs(SHOT, exist_ok=True)
ok = True


def line(t, m):
    global ok
    if t == '❌':
        ok = False
    print('%s %s' % (t, m))


PAGE = open(HTML, encoding='utf-8').read()
banned = ['代码:', '.hermes', 'profiles', 'SOUL', 'user_id', 'o9cq80', 'customer_attribution', '数据包',
          'baorui-sales', 'api_key', 'sk-', '/Users/', '.json', '.py', '赵云浩', '黄文才', '陈溪子',
          '超管', 'allowlist', '白名单', '脱敏', '已过滤', '隔离机制', 'token', 'brand_kit']
hits = [b for b in banned if b in PAGE]
line('✅' if not hits else '❌', '静态敏感串扫描：%s' % (hits or '无'))

ext, errs, con = [], [], []
with sync_playwright() as p:
    b = p.chromium.launch(channel='chrome')
    # 桌面
    pg = b.new_page(viewport={'width': 1100, 'height': 900})
    pg.on('request', lambda r: ext.append(r.url) if not r.url.startswith('file://') else None)
    pg.on('pageerror', lambda e: errs.append(str(e)))
    pg.on('console', lambda m: con.append(m.text) if m.type == 'error' else None)
    pg.goto('file://' + HTML, wait_until='networkidle')
    pg.wait_for_timeout(400)
    line('✅' if not ext else '❌', '外部请求 = %d %s' % (len(ext), ext[:2]))
    line('✅' if not errs and not con else '❌', 'page error=%d console error=%d' % (len(errs), len(con)))
    logo = pg.evaluate("(()=>{const i=document.querySelector('.bior-logo-chip img');return !!i&&i.complete&&i.naturalWidth>0})()")
    line('✅' if logo else '❌', 'Logo 实际解码 = %s' % logo)
    sl = pg.evaluate("document.querySelectorAll('.bior-slogan,.bior-footer-slogan').length")
    txt = pg.evaluate("(document.body.innerText.match(/守护生命健康，缔造美好生活/g)||[]).length")
    line('✅' if sl == 2 and txt == 2 else '❌', 'slogan 节点=%d 文本=%d（页眉+页脚应各 1）' % (sl, txt))
    secs = pg.evaluate("document.querySelectorAll('h2').length")
    scenes = pg.evaluate("document.querySelectorAll('.scene,.cap').length")
    line('✅' if secs >= 7 and scenes >= 30 else '❌', '结构：h2=%d 能力/场景卡=%d（应 ≥30）' % (secs, scenes))
    w = pg.evaluate("document.documentElement.scrollWidth")
    line('✅' if w <= 1130 else '❌', '桌面宽度 scrollWidth=%d（无横向溢出）' % w)
    pg.screenshot(path=os.path.join(SHOT, 'manual_desktop.png'), full_page=True)
    # 手机（她大概在微信里看）
    m = b.new_page(viewport={'width': 400, 'height': 860}, device_scale_factor=2)
    m.goto('file://' + HTML, wait_until='networkidle')
    m.wait_for_timeout(300)
    mw = m.evaluate("document.documentElement.scrollWidth")
    line('✅' if mw <= 410 else '❌', '手机宽度 scrollWidth=%d（≤410 无横向滚动）' % mw)
    m.screenshot(path=os.path.join(SHOT, 'manual_mobile.png'), full_page=True)
    b.close()
for f in sorted(os.listdir(SHOT)):
    print('   %s %.0f KB' % (f, os.path.getsize(os.path.join(SHOT, f)) / 1024.0))
print('总结论：%s' % ('✅ 全部通过' if ok else '❌ 有失败项'))
sys.exit(0 if ok else 1)
