#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""标题重复审计（可复跑回归）：
① 同一页「标题槽位」出现完全相同的文本（kick / h1 / h2 / 图题 / 图注 / SVG 图内文字 / 大字报 / 章号）
② 小标签(kick)整串被同页大标题(h1/h2)包含 —— 读者观感就是「同一个标题写了两次」
用法：/usr/bin/python3 _verify_price_deck_dupes.py   （需 playwright，非 exit 0 表示有重复）
"""
import os
import subprocess
import sys
import time
import urllib.parse

from playwright.sync_api import sync_playwright

W = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
DECK = os.path.join(W, '培训与上手', '培训', '价格谈判培训_攻心为上_deck.html')
PORT = 8806
URL = 'http://127.0.0.1:%d/%s' % (PORT, urllib.parse.quote(os.path.basename(DECK)))

SEL = (".pad .kick, .pad h1, .pad h2, .pad .fig-t, .pad figcaption, "
       ".pad svg text, .pad .mega-word, .pad .ch-num")

PROBE = """(sel) => {
  const out = [];
  document.querySelectorAll('#track > .slide').forEach((s, i) => {
    const texts = [];
    s.querySelectorAll(sel).forEach(e => {
      const t = (e.textContent || '').replace(/\\s+/g, ' ').trim();
      if (t) texts.push({t: t, cls: (e.tagName === 'text' ? 'svg:text' : (e.className || e.tagName).toString())});
    });
    const norm = {};
    texts.forEach(x => { (norm[x.t] = norm[x.t] || []).push(x.cls); });
    const dup = Object.keys(norm).filter(k => norm[k].length > 1).map(k => k + ' x' + norm[k].length);
    const kicks = texts.filter(x => /kick/.test(x.cls)).map(x => x.t);
    const heads = texts.filter(x => /^(t|t2)$/.test(x.cls)).map(x => x.t);
    const sub = [];
    kicks.forEach(k => heads.forEach(h => { if (k && h && h.includes(k)) sub.push(k + '  ⊂  ' + h); }));
    out.push({i: i + 1, sid: s.getAttribute('data-slide-id'), dup: dup, sub: sub});
  });
  return out;
}"""

srv = subprocess.Popen([sys.executable, '-m', 'http.server', str(PORT),
                        '--directory', os.path.join(W, '培训与上手', '培训')],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(1.4)
with sync_playwright() as p:
    br = p.chromium.launch(channel='chrome', headless=True)
    pg = br.new_page(viewport={'width': 1500, 'height': 900})
    pg.goto(URL)
    pg.wait_for_load_state('load')
    pg.wait_for_timeout(800)
    res = pg.evaluate(PROBE, SEL)
    br.close()
srv.terminate()

dup = [x for x in res if x['dup']]
sub = [x for x in res if x['sub']]
print('页数：%d' % len(res))
print('%s ① 标题槽位完全重复：%s' % ('✅' if not dup else '❌', len(dup)))
for x in dup:
    print('     p%-3d %-14s %s' % (x['i'], x['sid'], x['dup']))
print('%s ② 小标签被同页大标题包含：%s' % ('✅' if not sub else '❌', len(sub)))
for x in sub:
    print('     p%-3d %-14s %s' % (x['i'], x['sid'], x['sub']))
ok = not dup and not sub
print('\n%s' % ('标题重复审计通过 ✅' if ok else '存在重复标题 ❌'))
sys.exit(0 if ok else 1)
