#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""渲染验收：本地打开 HTML，抓控制台错误 + 截全页图 + 元素级检查。"""
import os, sys, json
from playwright.sync_api import sync_playwright

F = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                 '知识沉淀/适配体修饰Tth_罗氏CobasZ05_热启动对比_20261010.html')
SHOT = '/tmp/tth_report_full.png'
FIG1, FIG2 = '/tmp/tth_fig1.png', '/tmp/tth_fig2.png'

with sync_playwright() as p:
    b = p.chromium.launch(channel='chrome')   # 包内浏览器版本错位，改用系统 Chrome
    pg = b.new_page(viewport={'width': 1280, 'height': 1000}, device_scale_factor=2)
    errs, reqs = [], []
    pg.on('console', lambda m: errs.append(m.type + ': ' + m.text) if m.type == 'error' else None)
    pg.on('pageerror', lambda e: errs.append('pageerror: ' + str(e)))
    pg.on('request', lambda r: reqs.append(r.url) if not r.url.startswith('file:') else None)
    pg.goto('file://' + F)
    pg.wait_for_load_state('networkidle')
    pg.wait_for_timeout(1200)

    info = pg.evaluate("""() => {
      const q=s=>document.querySelector(s);
      const r=document.querySelector('.wrap').getBoundingClientRect();
      const svgs=[...document.querySelectorAll('svg.fig')].map(s=>{const b=s.getBoundingClientRect();return {w:Math.round(b.width),h:Math.round(b.height)}});
      return {
        title: document.title,
        h1: (q('h1')||{}).innerText || '',
        h2count: document.querySelectorAll('h2').length,
        kpi: document.querySelectorAll('.kpi').length,
        tables: document.querySelectorAll('table').length,
        rows: document.querySelectorAll('tbody tr').length,
        figN: svgs.length, figs: svgs,
        header: !!q('.bior-header'), footer: !!document.querySelector('footer,.bior-footer'),
        logo: !!document.querySelector('.bior-header img'),
        slogan: document.body.innerText.includes('守护生命健康，缔造美好生活'),
        hOverflow: document.documentElement.scrollWidth > window.innerWidth + 2,
        scrollW: document.documentElement.scrollWidth, innerW: window.innerWidth,
        emptyBlocks: [...document.querySelectorAll('div,section')].filter(e=>e.children.length===0&&!e.innerText.trim()&&!e.className.match(/kpi|card/)).length
      };
    }""")
    print(json.dumps(info, ensure_ascii=False, indent=2))
    print('\n控制台错误:', errs or '✅ 无')
    print('非 file:// 请求:', reqs or '✅ 无（零外链）')

    pg.screenshot(path=SHOT, full_page=True)
    for i, (sel, out) in enumerate([('svg.fig:nth-of-type(1)', FIG1), ('svg.fig:nth-of-type(2)', FIG2)]):
        el = pg.query_selector('svg.fig')
        allf = pg.query_selector_all('svg.fig')
        if allf and i < len(allf):
            allf[i].scroll_into_view_if_needed()
            pg.wait_for_timeout(300)
            allf[i].screenshot(path=out)
            print('图%d 截取: %s' % (i + 1, out))
    print('全页截图:', SHOT)
    b.close()
