"""测试自定义 XML 结构支持"""

import os
import sys
from hos_m2f.converters.docx_to_xml_lxml import DOCXToXMLLXMLConverter


def test_custom_xml_structures():
    """测试自定义 XML 结构支持"""
    print("测试自定义 XML 结构支持...")
    
    # 测试文件路径
    test_dir = "test_files"
    input_docx = os.path.join(test_dir, "test.docx")
    output_default = os.path.join(test_dir, "output_default.xml")
    output_docbook = os.path.join(test_dir, "output_docbook.xml")
    output_tei = os.path.join(test_dir, "output_tei.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:
        # 读取 DOCX 文件
        with open(input_docx, 'rb') as f:
            docx_content = f.read()
        
        # 初始化转换器
        converter = DOCXToXMLLXMLConverter()
        
        # 测试默认结构
        print("\n测试默认 XML 结构...")
        xml_content = converter.convert(
            input_content=docx_content,
            options={
                'xml_structure': 'default',
                'include_metadata': True,
                'include_structure': True,
                'include_formatting': True
            }
        )
        with open(output_default, 'wb') as f:
            f.write(xml_content)
        print(f"默认结构转换成功！输出文件: {output_default}")
        
        # 测试 DocBook 结构
        print("\n测试 DocBook XML 结构...")
        xml_content = converter.convert(
            input_content=docx_content,
            options={
                'xml_structure': 'docbook',
                'include_metadata': True,
                'include_formatting': True
            }
        )
        with open(output_docbook, 'wb') as f:
            f.write(xml_content)
        print(f"DocBook 结构转换成功！输出文件: {output_docbook}")
        
        # 测试 TEI 结构
        print("\n测试 TEI XML 结构...")
        xml_content = converter.convert(
            input_content=docx_content,
            options={
                'xml_structure': 'tei',
                'include_metadata': True,
                'include_formatting': True
            }
        )
        with open(output_tei, 'wb') as f:
            f.write(xml_content)
        print(f"TEI 结构转换成功！输出文件: {output_tei}")
        
        return True
    except Exception as e:
        print(f"转换失败: {e}")
        import traceback
        traceback.print_exc()
        return False


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