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

from typing import Any, Optional, Dict
from hos_m2f.converters.base_converter import BaseConverter
import ebooklib
from ebooklib import epub
import mistune


class MDToEPUBConverter(BaseConverter):
    """Markdown到EPUB格式转换器"""
    
    def convert(self, input_content: str, options: Optional[Dict[str, Any]] = None) -> bytes:
        """将Markdown转换为EPUB
        
        Args:
            input_content: Markdown内容
            options: 转换选项
            
        Returns:
            bytes: EPUB文件的二进制数据
        """
        if options is None:
            options = {}
        
        # 创建EPUB书籍
        book = epub.EpubBook()
        
        # 设置元数据
        book.set_identifier('id12345')
        book.set_title(options.get('title', 'Untitled'))
        book.set_language(options.get('language', 'zh'))
        book.add_author(options.get('author', 'Unknown'))
        
        # 添加封面
        if 'cover' in options:
            cover_image = epub.EpubItem(
                uid='cover-image',
                file_name='images/cover.jpg',
                media_type='image/jpeg',
                content=options['cover']
            )
            book.add_item(cover_image)
            book.set_cover('images/cover.jpg', cover_image)
        
        # 解析Markdown
        markdown = mistune.create_markdown(
            plugins=[
                'url',
                'abbr',
                'def_list',
                'footnotes',
                'tables',
                'task_lists',
                'strikethrough',
                'highlight',
                'superscript',
                'subscript'
            ]
        )
        
        # 转换为HTML
        html_content = markdown(input_content)
        
        # 创建章节
        chapter = epub.EpubHtml(
            title=options.get('title', 'Chapter 1'),
            file_name='chapter1.xhtml',
            lang='zh'
        )
        chapter.content = f'''
        <!DOCTYPE html>
        <html>
        <head>
            <title>{options.get('title', 'Untitled')}</title>
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>{options.get('title', 'Untitled')}</h1>
            {html_content}
        </body>
        </html>
        '''
        
        # 添加章节
        book.add_item(chapter)
        
        # 创建目录
        book.toc = [chapter]
        
        # 添加导航文件
        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())
        
        # 定义spine
        book.spine = ['nav', chapter]
        
        # 保存为二进制数据
        import io
        output = io.BytesIO()
        epub.write_epub(output, book, {})
        output.seek(0)
        
        return output.getvalue()
    
    def get_supported_formats(self) -> tuple:
        """获取支持的格式"""
        return ('markdown', 'epub')
