#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""PPTX→HTML deck 保真校验器
断言：原稿每一个表格单元格、每一段文本框文字，都原样出现在 HTML 中（一字不差）。
用法：/usr/bin/python3 脚本/verify_deck_fidelity.py <deck_model.json> <out.html>
退出码：0 = 全部命中；1 = 有未命中（列出）
"""
import json, io, re, sys, html as H

mf, hf = sys.argv[1], sys.argv[2]
m = json.load(open(mf, encoding='utf-8'))
s = io.open(hf, encoding='utf-8').read()
body = s.split('<body', 1)[1] if '<body' in s else s
norm = re.sub(r'[ \t\u3000\xa0]+', ' ', H.unescape(re.sub(r'<[^>]+>', '', body)))

miss, n = [], 0


def chk(v, where):
    global n
    for part in (v or '').split('\n'):
        part = re.sub(r'[ \t\u3000\xa0]+', ' ', part).strip()
        if not part:
            continue
        n += 1
        if part not in norm:
            miss.append((where, part[:60]))


for sl in m['slides']:
    for sh in sl['shapes']:
        if sh['kind'] == 'table':
            for ri, row in enumerate(sh['grid']):
                for ci, c in enumerate(row):
                    if not c.get('spanned'):
                        chk(c.get('t'), '第%d页 表r%dc%d' % (sl['n'], ri, ci))
        if sh['kind'] == 'text':
            chk((sh.get('txt') or {}).get('plain'), '第%d页 文本' % sl['n'])

print('校验单元 %d 个 / 未命中 %d 个' % (n, len(miss)))
for w, t in miss[:30]:
    print('   ❌ %s : %r' % (w, t))
if not miss:
    print('   ✅ 原稿全部文字与数字 100%% 原样保留')
sys.exit(1 if miss else 0)
