#!/usr/bin/env python3
"""
AI Analysis Service
AI分析服务
"""

from typing import List, Dict, Any, Optional

from python_core.utils.logger import logger
from ..types import SceneInfo, DetectionResult


class AIAnalysisService:
    """AI分析服务"""
    
    def __init__(self):
        self.ai_enabled = False
        self.llm = None

        # 尝试初始化AI分析器
        try:
            import os
            from langchain_anthropic import ChatAnthropic

            # 检查是否有API密钥
            api_key = os.getenv('ANTHROPIC_API_KEY')
            if not api_key:
                logger.info("ℹ️ 未设置ANTHROPIC_API_KEY环境变量，AI分析功能已禁用")
                self.ai_enabled = False
                return

            self.llm = ChatAnthropic(model="claude-3-5-sonnet-20241022", api_key=api_key)
            self.ai_enabled = True
            logger.info("✅ AI分析器初始化成功")
        except ImportError:
            logger.info("ℹ️ langchain_anthropic未安装，AI分析功能已禁用")
            self.ai_enabled = False
        except Exception as e:
            logger.warning(f"⚠️ AI分析器初始化失败: {e}")
            self.ai_enabled = False
    
    def analyze_detection_result(self, detection_result: DetectionResult, 
                               video_info: Dict[str, Any]) -> str:
        """分析检测结果"""
        if not self.ai_enabled:
            return "AI分析器未启用"
        
        try:
            analysis_prompt = self._create_analysis_prompt(detection_result, video_info)
            response = self.llm.invoke([{"role": "user", "content": analysis_prompt}])
            return response.content
            
        except Exception as e:
            error_msg = f"AI分析失败: {e}"
            logger.warning(error_msg)
            return error_msg
    
    def _create_analysis_prompt(self, result: DetectionResult, video_info: Dict[str, Any]) -> str:
        """创建分析提示词"""
        return f"""
请分析以下视频场景检测结果：

视频信息:
- 文件: {result.filename}
- 分辨率: {video_info.get('resolution', 'Unknown')}
- 时长: {result.total_duration:.2f}秒
- 帧率: {video_info.get('fps', 0):.2f}fps

检测结果:
- 检测器: {result.detector_type}
- 阈值: {result.threshold}
- 场景数: {result.total_scenes}
- 检测时间: {result.detection_time:.2f}秒

场景详情:
{self._format_scenes_for_ai(result.scenes)}

请提供:
1. 场景分布分析
2. 检测质量评估
3. 参数优化建议
4. 潜在问题识别
"""
    
    def _format_scenes_for_ai(self, scenes: List[SceneInfo]) -> str:
        """格式化场景信息供AI分析"""
        if not scenes:
            return "无场景数据"
        
        formatted = []
        for i, scene in enumerate(scenes[:10]):  # 只显示前10个场景
            formatted.append(
                f"场景 {i+1}: {scene.start_time:.2f}s - {scene.end_time:.2f}s "
                f"(时长: {scene.duration:.2f}s)"
            )
        
        if len(scenes) > 10:
            formatted.append(f"... 还有 {len(scenes) - 10} 个场景")
        
        return "\n".join(formatted)
