#!/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

    def batch_detect_and_split(self, video_paths: List[Path], output_base_dir: Optional[Path] = None,
                              detector_type: DetectorType = DetectorType.CONTENT, threshold: float = 30.0,
                              min_scene_length: float = 1.0, output_format: OutputFormat = OutputFormat.JSON,
                              enable_ai_analysis: bool = False, enable_video_splitting: bool = True,
                              max_concurrent: int = 2, continue_on_error: bool = True,
                              use_advanced_split: bool = True, split_quality: int = 23, split_preset: str = "fast",
                              max_video_duration: float = 60.0, request_id: Optional[str] = None) -> Dict[str, Any]:
        """批量场景检测和视频切分"""
        return self.workflow_manager.batch_detect_and_split(
            video_paths, output_base_dir, detector_type, threshold, min_scene_length,
            output_format, enable_ai_analysis, enable_video_splitting,
            max_concurrent, continue_on_error, use_advanced_split, split_quality, split_preset,
            max_video_duration, request_id
        )

