"""测试 XML Schema 验证功能"""

import os
import sys
from hos_m2f.converters.docx_to_xml_lxml import DOCXToXMLLXMLConverter
from lxml import etree as ET


def create_test_schema():
    """创建一个测试用的 XML Schema 文件"""
    print("创建测试 XML Schema 文件...")
    
    # 简单的测试 Schema
    schema_content = '''<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="document">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="metadata" minOccurs="0">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="author" type="xs:string" minOccurs="0"/>
                            <xs:element name="created" type="xs:string" minOccurs="0"/>
                            <xs:element name="modified" type="xs:string" minOccurs="0"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="content" minOccurs="0">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="paragraph" minOccurs="0" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="text" type="xs:string"/>
                                    </xs:sequence>
                                    <xs:attribute name="id" type="xs:string" use="required"/>
                                </xs:complexType>
                            </xs:element>
                            <xs:element name="heading" minOccurs="0" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="text" type="xs:string"/>
                                    </xs:sequence>
                                    <xs:attribute name="id" type="xs:string" use="required"/>
                                    <xs:attribute name="level" type="xs:string" use="required"/>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
'''
    
    # 保存 Schema 文件
    schema_path = os.path.join("test_files", "test_schema.xsd")
    with open(schema_path, 'w', encoding='utf-8') as f:
        f.write(schema_content)
    
    print(f"创建成功！文件: {schema_path}")
    return schema_path


def test_xml_schema_validation():
    """测试 XML Schema 验证功能"""
    print("测试 XML Schema 验证功能...")
    
    # 测试文件路径
    test_dir = "test_files"
    input_docx = os.path.join(test_dir, "test.docx")
    output_xml = os.path.join(test_dir, "output_validated.xml")
    
    # 确保测试目录存在
    os.makedirs(test_dir, exist_ok=True)
    
    # 检查输入文件是否存在
    if not os.path.exists(input_docx):
        print(f"错误：输入文件不存在: {input_docx}")
        print("请先运行 test_docx_to_xml.py 生成测试 DOCX 文件")
        return False
    
    try:
        # 创建测试 Schema
        schema_path = create_test_schema()
        
        # 读取 DOCX 文件
        with open(input_docx, 'rb') as f:
            docx_content = f.read()
        
        # 初始化转换器
        converter = DOCXToXMLLXMLConverter()
        
        # 转换（包含 Schema 验证）
        print("\n转换并验证 XML...")
        xml_content = converter.convert(
            input_content=docx_content,
            options={
                'xml_structure': 'default',
                'include_metadata': True,
                'include_structure': True,
                'include_formatting': True,
                'validate': True,
                'schema_path': schema_path
            }
        )
        
        # 保存输出
        with open(output_xml, 'wb') as f:
            f.write(xml_content)
        
        print(f"转换和验证成功！输出文件: {output_xml}")
        
        return True
    except Exception as e:
        print(f"转换或验证失败: {e}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == "__main__":
    success = test_xml_schema_validation()
    if success:
        print("\n测试通过！")
    else:
        print("\n测试失败，请检查错误信息。")
        sys.exit(1)
