"""XML修改模块"""

from typing import Dict, List
from lxml import etree as ET
import json


class XMLModifier:
    """XML修改器
    
    功能：
    1. 基于XPath修改XML内容
    2. 支持JSON Patch格式
    3. 实现AI指令到XML修改的转换
    """
    
    def __init__(self):
        """初始化修改器"""
        pass
    
    def modify_by_xpath(self, xml_content: str, xpath: str, new_content: str) -> str:
        """使用XPath修改XML
        
        Args:
            xml_content: XML内容字符串
            xpath: XPath表达式
            new_content: 新内容
            
        Returns:
            str: 修改后的XML
        """
        # 解析XML
        root = ET.fromstring(xml_content)
        
        # 查找元素
        elements = root.xpath(xpath)
        if elements:
            # 修改找到的第一个元素
            elements[0].text = new_content
        
        # 生成修改后的XML
        modified_xml = ET.tostring(root, pretty_print=True, encoding="unicode")
        
        return modified_xml
    
    def modify_by_json_patch(self, xml_content: str, patch_json: str) -> str:
        """使用JSON Patch修改XML
        
        Args:
            xml_content: XML内容字符串
            patch_json: JSON Patch格式的修改指令
            
        Returns:
            str: 修改后的XML
        """
        # 解析XML
        root = ET.fromstring(xml_content)
        
        # 解析JSON Patch
        patches = json.loads(patch_json)
        
        # 应用每个修改
        for patch in patches:
            if "xpath" in patch and "value" in patch:
                elements = root.xpath(patch["xpath"])
                if elements:
                    elements[0].text = patch["value"]
        
        # 生成修改后的XML
        modified_xml = ET.tostring(root, pretty_print=True, encoding="unicode")
        
        return modified_xml
    
    def modify_file(self, xml_file: str, modifications: List[Dict[str, str]], output_file: str = None) -> str:
        """修改XML文件
        
        Args:
            xml_file: XML文件路径
            modifications: 修改列表，每个元素为{"xpath": "...", "value": "..."}
            output_file: 输出文件路径（可选）
            
        Returns:
            str: 修改后的XML
        """
        # 读取XML文件，尝试不同编码
        encodings = ['utf-8', 'gbk', 'ansi']
        xml_content = None
        
        for encoding in encodings:
            try:
                with open(xml_file, 'r', encoding=encoding) as f:
                    xml_content = f.read()
                break
            except UnicodeDecodeError:
                continue
        
        if xml_content is None:
            raise Exception("无法读取文件：所有编码尝试都失败")
        
        # 解析XML
        root = ET.fromstring(xml_content)
        
        # 应用每个修改
        for modification in modifications:
            if "xpath" in modification and "value" in modification:
                elements = root.xpath(modification["xpath"])
                if elements:
                    elements[0].text = modification["value"]
        
        # 生成修改后的XML
        modified_xml = ET.tostring(root, pretty_print=True, encoding="unicode")
        
        # 如果指定了输出文件，保存修改后的XML
        if output_file:
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(modified_xml)
        
        return modified_xml
    
    def create_json_patch(self, modifications: List[Dict[str, str]]) -> str:
        """创建JSON Patch
        
        Args:
            modifications: 修改列表，每个元素为{"xpath": "...", "value": "..."}
            
        Returns:
            str: JSON Patch字符串
        """
        return json.dumps(modifications, ensure_ascii=False, indent=2)
