#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""验收：浏览器打开报告，断言 SVG 渲染、无 <title>、无外链；分段截图。"""
import os, sys, json
from playwright.sync_api import sync_playwright

F = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
    '/Users/liuxinyuan/Desktop/Hermes输出-工作类/知识沉淀/SEC-HPLC_测MIX中酶纯度与浓度_调研报告_20261010.html')
OUTDIR = os.path.join('/Users/liuxinyuan/Desktop/Hermes输出-工作类/.q3scratch', 'sec_shot')
os.makedirs(OUTDIR, exist_ok=True)
url = 'file://' + F

reqs = []
with sync_playwright() as p:
    b = p.chromium.launch(channel='chrome')
    pg = b.new_page(viewport={'width': 1280, 'height': 1000})
    pg.on('request', lambda r: reqs.append(r.url) if r.url.startswith(('http://', 'https://')) else None)
    errors = []
    pg.on('console', lambda m: errors.append(m.text) if m.type == 'error' else None)
    pg.goto(url, wait_until='load')
    pg.wait_for_timeout(900)

    info = pg.evaluate("""() => {
      const figs = [...document.querySelectorAll('svg.fig')];
      return {
        figCount: figs.length,
        svgNodes: document.querySelectorAll('svg').length,
        rectsVisible: [...document.querySelectorAll('svg.fig rect')].filter(r=>{
            const b=r.getBBox(); return b.width>0 && b.height>0;}).length,
        totalRects: document.querySelectorAll('svg.fig rect').length,
        titleInSvg: [...document.querySelectorAll('svg')].reduce((a,s)=>a+s.querySelectorAll('title').length,0),
        brInSvg: [...document.querySelectorAll('svg')].reduce((a,s)=>a+s.innerHTML.split('<br').length-1,0),
        sloganCount: (document.body.innerHTML.match(/守护生命健康/g)||[]).length,
        logoOk: (()=>{const i=document.querySelector('.bior-logo-chip img');return !!(i&&i.complete&&i.naturalWidth>0);})(),
        kpiCards: document.querySelectorAll('.kpi').length,
        tables: document.querySelectorAll('table').length,
        hOverflow: document.documentElement.scrollWidth > window.innerWidth+4,
        docH: document.body.scrollHeight
      };
    }""")
    print(json.dumps(info, ensure_ascii=False, indent=1))
    print('external requests:', reqs)
    print('console errors:', errors)

    # 分段截图
    ans = {}
    figshots = []
    for i, el in enumerate(pg.query_selector_all('svg.fig')):
        el.scroll_into_view_if_needed(); pg.wait_for_timeout(250)
        fp = os.path.join(OUTDIR, 'fig_%d.png' % (i + 1))
        el.screenshot(path=fp); figshots.append(fp)
    # 全页 + 顶部两段
    pg.screenshot(path=os.path.join(OUTDIR, 'full.png'), full_page=True)
    pg.evaluate("window.scrollTo(0,0)"); pg.wait_for_timeout(200)
    pg.screenshot(path=os.path.join(OUTDIR, 'sec_top.png'))
    pg.evaluate("window.scrollTo(0, Math.floor(document.body.scrollHeight*0.45))"); pg.wait_for_timeout(300)
    pg.screenshot(path=os.path.join(OUTDIR, 'sec_mid.png'))
    b.close()

print('shots:')
for f in figshots + [os.path.join(OUTDIR, 'full.png'),
                     os.path.join(OUTDIR, 'sec_top.png'),
                     os.path.join(OUTDIR, 'sec_mid.png')]:
    print(' ', f, os.path.getsize(f), 'bytes')
