"""测试图片提取和加密功能"""

import os
import tempfile
import shutil
from hos_m2f.resources.resource_manager import ResourceManager
from hos_m2f.converters.xml_to_docx import XMLToDOCXConverter
import xml.etree.ElementTree as ET


def test_image_degradation():
    """测试图片降质功能"""
    # 创建资源管理器
    with tempfile.TemporaryDirectory() as temp_dir:
        resource_manager = ResourceManager(temp_dir)
        
        # 创建一个简单的测试图片
        test_image_path = os.path.join(temp_dir, "test_image.png")
        from PIL import Image
        img = Image.new('RGB', (100, 100), color='red')
        img.save(test_image_path)
        
        # 测试图片降质
        degraded_image_path = os.path.join(temp_dir, "degraded_test_image.png")
        result = resource_manager.degrade_image(test_image_path, degraded_image_path)
        
        # 验证降质是否成功
        assert result == True
        assert os.path.exists(degraded_image_path)
        
        # 验证降质后的图片存在
        degraded_img = Image.open(degraded_image_path)
        assert degraded_img is not None
        print("✓ 图片降质功能测试通过")


def test_image_extraction():
    """测试图片提取功能"""
    # 创建资源管理器
    with tempfile.TemporaryDirectory() as temp_dir:
        resource_manager = ResourceManager(temp_dir)
        
        # 测试从DOCX提取图片（如果有测试文件）
        test_docx_path = os.path.join(os.path.dirname(__file__), "test_document.docx")
        if os.path.exists(test_docx_path):
            extracted_images = resource_manager.extract_images_from_file(test_docx_path)
            print(f"✓ 从DOCX提取了 {len(extracted_images)} 张图片")
        
        # 测试从PDF提取图片（如果有测试文件）
        test_pdf_path = os.path.join(os.path.dirname(__file__), "test_document.pdf")
        if os.path.exists(test_pdf_path):
            extracted_images = resource_manager.extract_images_from_file(test_pdf_path)
            print(f"✓ 从PDF提取了 {len(extracted_images)} 张图片")


def test_encrypt_mode_conversion():
    """测试加密模式下的XML到DOCX转换"""
    # 创建测试XML内容，包含图片
    test_xml = """
    <document>
        <metadata>
            <title>Test Document</title>
            <author>Test Author</author>
        </metadata>
        <content>
            <paragraph>
                <text>Test paragraph with image</text>
                <image src="test_image.png" alt="Test Image" />
            </paragraph>
        </content>
    </document>
    """
    
    # 创建临时目录和测试图片
    with tempfile.TemporaryDirectory() as temp_dir:
        # 创建测试图片
        test_image_path = os.path.join(temp_dir, "test_image.png")
        from PIL import Image
        img = Image.new('RGB', (100, 100), color='blue')
        img.save(test_image_path)
        
        # 创建assets/images目录
        os.makedirs(os.path.join(temp_dir, "assets", "images"), exist_ok=True)
        shutil.copy(test_image_path, os.path.join(temp_dir, "assets", "images", "test_image.png"))
        
        # 测试正常模式转换
        converter = XMLToDOCXConverter()
        normal_result = converter.convert(
            test_xml.encode('utf-8'),
            {
                'base_dir': temp_dir,
                'encrypt': False
            }
        )
        assert len(normal_result) > 0
        print("✓ 正常模式XML到DOCX转换测试通过")
        
        # 测试加密模式转换
        encrypt_result = converter.convert(
            test_xml.encode('utf-8'),
            {
                'base_dir': temp_dir,
                'encrypt': True
            }
        )
        assert len(encrypt_result) > 0
        print("✓ 加密模式XML到DOCX转换测试通过")


def test_standalone_image_element():
    """测试独立的图片元素处理"""
    # 创建测试XML内容，包含独立的图片元素
    test_xml = """
    <document>
        <metadata>
            <title>Test Document</title>
        </metadata>
        <content>
            <image src="test_image.png" alt="Standalone Test Image" />
        </content>
    </document>
    """
    
    # 创建临时目录和测试图片
    with tempfile.TemporaryDirectory() as temp_dir:
        # 创建测试图片
        test_image_path = os.path.join(temp_dir, "test_image.png")
        from PIL import Image
        img = Image.new('RGB', (150, 150), color='green')
        img.save(test_image_path)
        
        # 创建assets/images目录
        os.makedirs(os.path.join(temp_dir, "assets", "images"), exist_ok=True)
        shutil.copy(test_image_path, os.path.join(temp_dir, "assets", "images", "test_image.png"))
        
        # 测试加密模式转换
        converter = XMLToDOCXConverter()
        result = converter.convert(
            test_xml.encode('utf-8'),
            {
                'base_dir': temp_dir,
                'encrypt': True
            }
        )
        assert len(result) > 0
        print("✓ 独立图片元素处理测试通过")


if __name__ == "__main__":
    print("开始测试图片提取和加密功能...")
    
    try:
        test_image_degradation()
    except Exception as e:
        print(f"✗ 图片降质功能测试失败: {e}")
    
    try:
        test_image_extraction()
    except Exception as e:
        print(f"✗ 图片提取功能测试失败: {e}")
    
    try:
        test_encrypt_mode_conversion()
    except Exception as e:
        print(f"✗ 加密模式转换测试失败: {e}")
    
    try:
        test_standalone_image_element()
    except Exception as e:
        print(f"✗ 独立图片元素处理测试失败: {e}")
    
    print("测试完成!")
