"""XML到Markdown格式转换器"""

from typing import Any, Optional, Dict
from hos_m2f.converters.base_converter import BaseConverter
import xml.etree.ElementTree as ET


class XMLToMDConverter(BaseConverter):
    """XML到Markdown格式转换器"""
    
    def convert(self, input_content: bytes, options: Optional[Dict[str, Any]] = None) -> bytes:
        """将XML转换为Markdown
        
        Args:
            input_content: XML文件的二进制数据
            options: 转换选项
            
        Returns:
            bytes: Markdown文件的二进制数据
        """
        if options is None:
            options = {}
        
        # 解析XML
        root = ET.fromstring(input_content)
        
        # 转换为Markdown
        md_content = self._xml_to_md(root)
        
        return md_content.encode('utf-8')
    
    def _xml_to_md(self, element: ET.Element, indent: int = 0) -> str:
        """将XML元素转换为Markdown
        
        Args:
            element: XML元素
            indent: 缩进级别
            
        Returns:
            str: Markdown字符串
        """
        md_parts = []
        prefix = '  ' * indent
        
        # 处理元素内容
        if element.text and element.text.strip():
            # 处理标题
            if element.tag in ['heading', 'title', 'Header', 'Title']:
                md_parts.append('#' * (indent + 1) + ' ' + element.text.strip())
            # 处理段落
            elif element.tag in ['paragraph', 'p', 'Paragraph']:
                md_parts.append(element.text.strip())
            # 处理列表项
            elif element.tag in ['list_item', 'item', 'ListItem']:
                md_parts.append(f'{prefix}- {element.text.strip()}')
            # 处理代码块
            elif element.tag in ['code_block', 'code', 'Code']:
                language = element.get('language', '')
                md_parts.append(f'```{language}' if language else '```')
                md_parts.append(element.text.strip())
                md_parts.append('```')
            # 处理普通文本
            else:
                md_parts.append(f'{prefix}{element.tag}: {element.text.strip()}')
        
        # 处理子元素
        for child in element:
            # 处理列表
            if child.tag in ['list', 'List']:
                list_type = child.get('type', 'unordered')
                md_parts.append(f'{prefix}{child.tag}:')
                for item in child:
                    if item.tag in ['list_item', 'item', 'ListItem']:
                        item_text = item.text.strip() if item.text else ''
                        md_parts.append(f'{prefix}- {item_text}')
            # 处理表格
            elif child.tag in ['table', 'Table']:
                # 提取表头
                headers = []
                for header in child.findall('.//header'):
                    headers.append(header.text.strip() if header.text else '')
                
                if headers:
                    # 生成表格
                    md_parts.append('| ' + ' | '.join(headers) + ' |')
                    md_parts.append('| ' + ' | '.join(['---'] * len(headers)) + ' |')
                    
                    # 提取表格数据
                    for row in child.findall('.//row'):
                        cells = []
                        for cell in row:
                            cells.append(cell.text.strip() if cell.text else '')
                        if cells:
                            md_parts.append('| ' + ' | '.join(cells) + ' |')
            # 处理其他子元素
            else:
                child_md = self._xml_to_md(child, indent + 1)
                if child_md:
                    md_parts.append(child_md)
        
        # 添加空行
        if md_parts:
            md_parts.append('')
        
        return '\n'.join(md_parts)
    
    def get_supported_formats(self) -> tuple:
        """获取支持的格式"""
        return ('xml', 'markdown')
