#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""图形排版取证：所有 SVG 文本是否越界 / 相互重叠（独立于截图）。"""
import os

from playwright.sync_api import sync_playwright

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
HTML = 'file://' + os.path.join(ROOT, '销售分析', '_集团维度_增减归因.html')


def main():
    with sync_playwright() as p:
        b = p.chromium.launch(channel='chrome')
        pg = b.new_page(viewport={'width': 1440, 'height': 1000})
        pg.goto(HTML, wait_until='networkidle')
        res = pg.evaluate("""() => {
          const W=1440, out={oob:[],ovlp:[],bars:0,texts:0};
          for(const sv of document.querySelectorAll('svg')){
            const sb=sv.getBoundingClientRect();
            const texts=[...sv.querySelectorAll('text')];
            out.texts+=texts.length;
            out.bars+=sv.querySelectorAll('rect').length;
            const boxes=[];
            for(const t of texts){
              const r=t.getBoundingClientRect();
              if(r.left<sb.left-1||r.right>sb.right+1||r.top<sb.top-1||r.bottom>sb.bottom+1)
                out.oob.push(t.textContent+' @ '+Math.round(r.left)+','+Math.round(r.top));
              boxes.push({s:t.textContent,l:r.left,t:r.top,r:r.right,b:r.bottom});
            }
            // 文本两两重叠（面积 > 30% 较小者）
            for(let i=0;i<boxes.length;i++)for(let j=i+1;j<boxes.length;j++){
              const a=boxes[i],c=boxes[j];
              const ox=Math.min(a.r,c.r)-Math.max(a.l,c.l), oy=Math.min(a.b,c.b)-Math.max(a.t,c.t);
              if(ox>0&&oy>0){
                const ar=(a.r-a.l)*(a.b-a.t), cr=(c.r-c.l)*(c.b-c.t);
                if(ox*oy > 0.30*Math.min(ar,cr)) out.ovlp.push(a.s+' × '+c.s);
              }
            }
          }
          return out;
        }""")
        b.close()
    print('文本节点 =', res['texts'], ' 条形(rect) =', res['bars'])
    print('越界文本 =', len(res['oob']), res['oob'][:6])
    print('重叠文本对 =', len(res['ovlp']), res['ovlp'][:6])
    assert not res['oob'] and not res['ovlp'], '存在越界/重叠'


if __name__ == '__main__':
    main()
