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

from typing import Any, Optional, Dict
from hos_m2f.converters.base_converter import BaseConverter
from docx import Document


class DOCXToMDConverter(BaseConverter):
    """DOCX到Markdown格式转换器"""
    
    def convert(self, input_content: bytes, options: Optional[Dict[str, Any]] = None) -> bytes:
        """将DOCX转换为Markdown
        
        Args:
            input_content: DOCX文件的二进制数据
            options: 转换选项
            
        Returns:
            bytes: Markdown文件的二进制数据
        """
        if options is None:
            options = {}
        
        # 加载DOCX文档
        import io
        doc = Document(io.BytesIO(input_content))
        
        # 转换为Markdown
        md_content = []
        
        # 处理段落
        for paragraph in doc.paragraphs:
            # 处理标题
            if paragraph.style.name.startswith('Heading'):
                level = int(paragraph.style.name.split(' ')[1])
                md_content.append('#' * level + ' ' + paragraph.text)
            # 处理列表
            elif paragraph.style.name in ['List Bullet', 'List Number']:
                # 检测缩进级别
                indent_level = int(paragraph.paragraph_format.left_indent.inches // 0.5)
                prefix = '  ' * indent_level
                
                if paragraph.style.name == 'List Number':
                    # 简化处理，实际项目中需要更复杂的列表编号处理
                    md_content.append(prefix + '1. ' + paragraph.text)
                else:
                    md_content.append(prefix + '- ' + paragraph.text)
            # 处理普通段落
            else:
                if paragraph.text:
                    md_content.append(paragraph.text)
            
            # 添加空行
            md_content.append('')
        
        # 处理表格
        for table in doc.tables:
            # 表头
            headers = []
            for cell in table.rows[0].cells:
                headers.append(cell.text)
            
            # 表格分隔线
            separators = ['---'] * len(headers)
            
            # 表格数据
            rows = []
            for row in table.rows[1:]:
                row_cells = []
                for cell in row.cells:
                    row_cells.append(cell.text)
                rows.append(row_cells)
            
            # 生成Markdown表格
            if headers:
                md_content.append('| ' + ' | '.join(headers) + ' |')
                md_content.append('| ' + ' | '.join(separators) + ' |')
                for row in rows:
                    md_content.append('| ' + ' | '.join(row) + ' |')
                md_content.append('')
        
        # 生成Markdown内容
        md_text = '\n'.join(md_content)
        
        return md_text.encode('utf-8')
    
    def get_supported_formats(self) -> tuple:
        """获取支持的格式"""
        return ('docx', 'markdown')
