"""
LLM-based Podcast Script Converter

将HTML内容转换为播客风格的稿件，支持多种LLM模型接口。
"""

import os
import logging
from abc import ABC, abstractmethod
from typing import Optional, Dict, Literal
import html2text

# 第三方库导入（需要额外安装）
try:
    from openai import OpenAI  # OpenAI官方库
    import google.generativeai as genai  # Google Gemini
except ImportError:
    pass  # 运行时检查

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class LLMConverter(ABC):
    """LLM转换器抽象基类"""
    
    @abstractmethod
    def convert_to_podcast(self, html_content: str) -> Optional[str]:
        """将HTML内容转换为播客稿件"""
        pass

class OpenAIConverter(LLMConverter):
    """ChatGPT转换器实现"""
    
    def __init__(self, model: str = "gpt-4-turbo", temperature: float = 0.7):
        self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
        self.model = model
        self.temperature = temperature
        
    def convert_to_podcast(self, html_content: str) -> Optional[str]:
        try:
            # 将HTML转换为Markdown格式
            markdown_content = html2text.html2text(html_content)
            
            response = self.client.chat.completions.create(
                model=self.model,
                temperature=self.temperature,
                messages=[
                    {
                        "role": "system",
                        "content": """你是一位专业播客编剧，需要将技术文章转换为生动有趣的播客稿件。要求：
1. 使用口语化表达，避免专业术语
2. 结构清晰，包含引言、主体和总结
3. 突出文章的核心观点和技术亮点
4. 适当添加过渡语和互动提示
5. 总长度控制在1500字左右"""
                    },
                    {
                        "role": "user",
                        "content": markdown_content
                    }
                ]
            )
            return response.choices[0].message.content
        except Exception as e:
            logger.error(f"OpenAI转换失败: {str(e)}")
            return None

class GeminiConverter(LLMConverter):
    """Google Gemini转换器实现"""
    
    def __init__(self, model: str = "gemini-pro", temperature: float = 0.7):
        genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
        self.model = genai.GenerativeModel(model)
        self.temperature = temperature
        
    def convert_to_podcast(self, html_content: str) -> Optional[str]:
        try:
            markdown_content = html2text.html2text(html_content)
            
            response = self.model.generate_content(
                f"[播客稿件转换要求同OpenAI版本]\n\n{markdown_content}",
                generation_config=genai.types.GenerationConfig(
                    temperature=self.temperature
                )
            )
            return response.text
        except Exception as e:
            logger.error(f"Gemini转换失败: {str(e)}")
            return None

class DeepSeekConverter(LLMConverter):
    """深度求索转换器实现"""
    
    def __init__(self, model: str = "deepseek-chat", temperature: float = 0.7):
        self.client = OpenAI(
            api_key=os.getenv("DEEPSEEK_API_KEY"),
            base_url="https://api.deepseek.com/v1"
        )
        self.model = model
        self.temperature = temperature
        
    def convert_to_podcast(self, html_content: str) -> Optional[str]:
        try:
            markdown_content = html2text.html2text(html_content)
            
            response = self.client.chat.completions.create(
                model=self.model,
                temperature=self.temperature,
                messages=[
                    {"role": "system", "content": "[播客稿件转换要求同OpenAI版本]"},
                    {"role": "user", "content": markdown_content}
                ]
            )
            return response.choices[0].message.content
        except Exception as e:
            logger.error(f"DeepSeek转换失败: {str(e)}")
            return None

class PodcastConverter:
    """播客稿件转换管理器"""
    
    def __init__(
        self,
        provider: Literal["openai", "gemini", "deepseek"] = "openai",
        model: Optional[str] = None,
        temperature: float = 0.7
    ):
        self.provider = provider
        self.model = model
        self.temperature = temperature
        self.converter = self._init_converter()
        
    def _init_converter(self) -> LLMConverter:
        """初始化指定的LLM转换器"""
        try:
            if self.provider == "openai":
                return OpenAIConverter(
                    model=self.model or "gpt-4-turbo",
                    temperature=self.temperature
                )
            elif self.provider == "gemini":
                return GeminiConverter(
                    model=self.model or "gemini-pro",
                    temperature=self.temperature
                )
            elif self.provider == "deepseek":
                return DeepSeekConverter(
                    model=self.model or "deepseek-chat",
                    temperature=self.temperature
                )
            else:
                raise ValueError("不支持的LLM提供商")
        except Exception as e:
            logger.error(f"转换器初始化失败: {str(e)}")
            raise

    def convert(self, html_content: str) -> Optional[str]:
        """执行转换流程"""
        if not html_content:
            logger.warning("输入内容为空")
            return None
            
        logger.info(f"开始转换，使用模型: {self.provider}/{self.model}")
        return self.converter.convert_to_podcast(html_content)

# 使用示例
if __name__ == "__main__":
    # 测试用HTML内容（实际应从文件或网络获取）
    sample_html = """
    <html>
        <body>
            <h1>人工智能的未来发展</h1>
            <p>近年来，AI技术取得了突破性进展...</p>
            <ul>
                <li>自然语言处理的进步</li>
                <li>计算机视觉的应用扩展</li>
                <li>伦理问题的重要性</li>
            </ul>
        </body>
    </html>
    """
    
    # 使用OpenAI转换
    openai_converter = PodcastConverter(provider="openai")
    result = openai_converter.convert(sample_html)
    
    if result:
        print("转换结果示例：")
        print(result[:500] + "...")  # 打印前500字符
    else:
        print("转换失败")