#!/usr/bin/env python3
"""
检查Word模板的结构，特别是签发机关和有效期部分
"""

import sys
import zipfile
import re
from pathlib import Path
import xml.etree.ElementTree as ET

def check_template_structure(docx_path):
    """检查模板结构"""
    try:
        with zipfile.ZipFile(docx_path, 'r') as zip_ref:
            # 读取document.xml
            with zip_ref.open('word/document.xml') as f:
                content = f.read().decode('utf-8')
                
                # 查找包含back_issuing_authority的段落
                print("=" * 60)
                print("签发机关部分:")
                print("=" * 60)
                
                # 查找包含back_issuing_authority的文本
                pattern = r'<w:p[^>]*>.*?back_issuing_authority.*?</w:p>'
                matches = re.findall(pattern, content, re.DOTALL)
                
                for i, match in enumerate(matches, 1):
                    print(f"\n段落 {i}:")
                    # 提取纯文本
                    text_pattern = r'<w:t[^>]*>(.*?)</w:t>'
                    texts = re.findall(text_pattern, match)
                    print("  文本内容:", ''.join(texts))
                
                print("\n" + "=" * 60)
                print("有效期部分:")
                print("=" * 60)
                
                # 查找包含valid的段落
                pattern = r'<w:p[^>]*>.*?valid.*?</w:p>'
                matches = re.findall(pattern, content, re.DOTALL)
                
                for i, match in enumerate(matches, 1):
                    print(f"\n段落 {i}:")
                    # 提取纯文本
                    text_pattern = r'<w:t[^>]*>(.*?)</w:t>'
                    texts = re.findall(text_pattern, match)
                    print("  文本内容:", ''.join(texts))
                
    except Exception as e:
        print(f"错误: {e}", file=sys.stderr)
        return False
    
    return True

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("用法: python check_template_structure.py <docx文件路径>")
        sys.exit(1)
    
    docx_path = sys.argv[1]
    
    if not Path(docx_path).exists():
        print(f"文件不存在: {docx_path}", file=sys.stderr)
        sys.exit(1)
    
    check_template_structure(docx_path)
