#!/usr/bin/env python3
"""
Scene Detector Main Interface
场景检测主接口类

整合所有功能的主要接口类，提供简洁的API
"""

from pathlib import Path
from typing import Dict, Any, Optional, List
from dataclasses import asdict

from python_core.utils.logger import logger
from .types import DetectorType, OutputFormat, DetectionResult
from .services import SceneDetectorService, VideoInfoService, AIAnalysisService
from .workflows import SceneDetectionWorkflowManager
from .utils import ResultSaver, InputValidator


class SceneDetector:
    """场景检测器主类"""

    def __init__(self):
        self.supported_formats = {'.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm', '.m4v'}
        
        # 初始化服务
        self.detector_service = SceneDetectorService()
        self.video_info_service = VideoInfoService()
        self.ai_analysis_service = AIAnalysisService()
        
        # 初始化工作流管理器
        self.workflow_manager = SceneDetectionWorkflowManager()
        
        # 初始化工具类
        self.result_saver = ResultSaver()
        self.input_validator = InputValidator(self.supported_formats)

    def detect_scenes(self, video_path: Path, detector_type: DetectorType = DetectorType.CONTENT,
                     threshold: float = 30.0, min_scene_length: float = 1.0) -> DetectionResult:
        """基础场景检测方法"""
        return self.detector_service.detect_scenes(video_path, detector_type, threshold, min_scene_length)

    def get_video_info(self, video_path: Path) -> Dict[str, Any]:
        """获取视频信息"""
        try:
            # 验证文件
            self.video_info_service.validate_video_file(video_path, self.supported_formats)
            
            # 提取信息
            video_info = self.video_info_service.extract_video_info(video_path)
            
            return {
                "success": True,
                "info": video_info
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }

    def detect_with_workflow(self, video_path: Path, detector_type: DetectorType = DetectorType.CONTENT,
                           threshold: float = 30.0, min_scene_length: float = 1.0,
                           output_path: Optional[Path] = None, output_format: OutputFormat = OutputFormat.JSON,
                           enable_ai_analysis: bool = True, request_id: Optional[str] = None) -> Dict[str, Any]:
        """使用LangGraph工作流进行场景检测"""
        return self.workflow_manager.detect_with_workflow(
            video_path, detector_type, threshold, min_scene_length,
            output_path, output_format, enable_ai_analysis, request_id
        )

    def save_results(self, result: DetectionResult, output_path: Path, 
                    output_format: OutputFormat) -> None:
        """保存检测结果"""
        self.result_saver.save_results(result, output_path, output_format)

    def batch_detect(self, video_paths: List[Path], detector_type: DetectorType = DetectorType.CONTENT,
                    threshold: float = 30.0, min_scene_length: float = 1.0,
                    output_dir: Optional[Path] = None, output_format: OutputFormat = OutputFormat.JSON) -> List[Dict[str, Any]]:
        """批量检测场景"""
        results = []
        
        for video_path in video_paths:
            try:
                logger.info(f"🎬 处理视频: {video_path.name}")
                
                # 检测场景
                result = self.detect_scenes(video_path, detector_type, threshold, min_scene_length)
                
                # 保存结果（如果指定了输出目录）
                if output_dir and result.success:
                    output_file = output_dir / f"{video_path.stem}_scenes.{output_format.value}"
                    self.save_results(result, output_file, output_format)
                
                # 序列化结果
                serialized_result = {
                    "video_path": str(video_path),
                    "success": result.success,
                    "result": asdict(result) if result.success else None,
                    "error": result.error
                }
                
                results.append(serialized_result)
                
            except Exception as e:
                logger.error(f"❌ 处理视频失败 {video_path.name}: {e}")
                results.append({
                    "video_path": str(video_path),
                    "success": False,
                    "result": None,
                    "error": str(e)
                })
        
        return results

    # JSON-RPC方法
    def jsonrpc_detect_scenes(self, video_path: str, detector_type: str = "content",
                            threshold: float = 30.0, min_scene_length: float = 1.0) -> Dict[str, Any]:
        """JSON-RPC方法：基础场景检测"""
        try:
            result = self.detect_scenes(
                Path(video_path),
                DetectorType(detector_type),
                threshold,
                min_scene_length
            )
            
            return asdict(result)
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }

    def jsonrpc_get_video_info(self, video_path: str) -> Dict[str, Any]:
        """JSON-RPC方法：获取视频信息"""
        try:
            return self.get_video_info(Path(video_path))
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }

    def jsonrpc_detect_with_workflow(self, video_path: str, detector_type: str = "content",
                                   threshold: float = 30.0, min_scene_length: float = 1.0,
                                   output_path: Optional[str] = None, output_format: str = "json",
                                   enable_ai_analysis: bool = True, request_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
        """JSON-RPC方法：工作流场景检测"""
        try:
            output_path_obj = Path(output_path) if output_path else None

            result = self.detect_with_workflow(
                Path(video_path),
                DetectorType(detector_type),
                threshold,
                min_scene_length,
                output_path_obj,
                OutputFormat(output_format),
                enable_ai_analysis,
                request_id
            )

            # 检查是否是JSON-RPC模式
            if result.get("jsonrpc_mode"):
                # JSON-RPC模式：结果已经通过工作流发送，返回None
                return None
            else:
                # 非JSON-RPC模式：序列化并返回结果
                serialized_result = {}
                for key, value in result.items():
                    if key == "detection_result" and value:
                        serialized_result[key] = asdict(value)
                    else:
                        serialized_result[key] = value
                return serialized_result

        except Exception as e:
            # 如果有request_id，错误已经在detect_with_workflow中发送
            if request_id:
                return None
            else:
                return {
                    "success": False,
                    "error": str(e)
                }

    def jsonrpc_batch_detect(self, video_paths: List[str], detector_type: str = "content",
                           threshold: float = 30.0, min_scene_length: float = 1.0,
                           output_dir: Optional[str] = None, output_format: str = "json") -> Dict[str, Any]:
        """JSON-RPC方法：批量检测"""
        try:
            paths = [Path(p) for p in video_paths]
            output_dir_obj = Path(output_dir) if output_dir else None
            
            results = self.batch_detect(
                paths,
                DetectorType(detector_type),
                threshold,
                min_scene_length,
                output_dir_obj,
                OutputFormat(output_format)
            )
            
            return {
                "success": True,
                "results": results,
                "total_videos": len(video_paths),
                "successful_detections": sum(1 for r in results if r["success"])
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }

    def register_jsonrpc_methods(self):
        """注册JSON-RPC方法到全局注册器"""
        from python_core.utils.jsonrpc_enhanced import method_registry
        
        # 直接注册方法
        method_registry.register_function(self.jsonrpc_detect_scenes, "scene.detect")
        method_registry.register_function(self.jsonrpc_detect_with_workflow, "scene.detect_workflow")
        method_registry.register_function(self.jsonrpc_get_video_info, "scene.get_video_info")
        method_registry.register_function(self.jsonrpc_batch_detect, "scene.batch_detect")
