"""
单个文件场景检测器
提供单个视频文件的场景检测和切分功能
"""

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

from python_core.utils.logger import logger
from .workflows.single_workflow_manager import SingleWorkflowManager
from .types.enums import DetectorType, OutputFormat


class SingleSceneDetector:
    """单个文件场景检测器"""
    
    def __init__(self):
        self.workflow_manager = SingleWorkflowManager()
        logger.info("SingleSceneDetector 初始化完成")
    
    def detect_and_split(
        self,
        video_path: str | Path,
        output_dir: Optional[str | 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,
        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]:
        """
        单个视频文件的场景检测和切分
        
        Args:
            video_path: 视频文件路径
            output_dir: 输出目录，如果为None则使用视频文件同目录
            detector_type: 检测器类型 (content/threshold/adaptive)
            threshold: 检测阈值 (0-100)
            min_scene_length: 最小场景长度（秒）
            output_format: 输出格式 (json/csv/txt)
            enable_ai_analysis: 是否启用AI分析
            enable_video_splitting: 是否启用视频切分
            use_advanced_split: 是否使用高级切分
            split_quality: 切分质量 (CRF值, 18-28)
            split_preset: 编码预设 (ultrafast/fast/medium/slow)
            max_video_duration: 最大视频时长限制（秒）
            request_id: 请求ID（用于JSON-RPC进度报告）
            
        Returns:
            Dict: 处理结果
        """
        
        # 转换路径
        video_path = Path(video_path)
        output_dir = Path(output_dir) if output_dir else None
        
        return self.workflow_manager.detect_and_split_single_video(
            video_path=video_path,
            output_dir=output_dir,
            detector_type=detector_type,
            threshold=threshold,
            min_scene_length=min_scene_length,
            output_format=output_format,
            enable_ai_analysis=enable_ai_analysis,
            enable_video_splitting=enable_video_splitting,
            use_advanced_split=use_advanced_split,
            split_quality=split_quality,
            split_preset=split_preset,
            max_video_duration=max_video_duration,
            request_id=request_id
        )
    
    def import_to_project(
        self,
        video_path: str | Path,
        project_id: str,
        project_directory: str | Path,
        material_tags: Optional[List[str]] = None,
        detector_type: DetectorType = DetectorType.CONTENT,
        threshold: float = 30.0,
        min_scene_length: float = 1.0,
        split_quality: int = 23,
        split_preset: str = "fast",
        max_video_duration: float = 2.0,
        request_id: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        导入单个视频到项目素材库
        
        Args:
            video_path: 视频文件路径
            project_id: 项目ID
            project_directory: 项目目录
            material_tags: 素材标签列表
            detector_type: 检测器类型
            threshold: 检测阈值
            min_scene_length: 最小场景长度
            split_quality: 切分质量
            split_preset: 编码预设
            max_video_duration: 最大视频时长限制
            request_id: 请求ID
            
        Returns:
            Dict: 导入结果
        """
        
        # 转换路径
        video_path = Path(video_path)
        project_directory = Path(project_directory)
        
        return self.workflow_manager.detect_and_split_for_project(
            video_path=video_path,
            project_id=project_id,
            project_directory=project_directory,
            material_tags=material_tags,
            detector_type=detector_type,
            threshold=threshold,
            min_scene_length=min_scene_length,
            split_quality=split_quality,
            split_preset=split_preset,
            max_video_duration=max_video_duration,
            request_id=request_id
        )
    
    def validate_video(self, video_path: str | Path) -> Dict[str, Any]:
        """
        验证视频文件
        
        Args:
            video_path: 视频文件路径
            
        Returns:
            Dict: 验证结果
        """
        video_path = Path(video_path)
        
        result = {
            "valid": False,
            "path": str(video_path),
            "exists": False,
            "is_file": False,
            "supported_format": False,
            "file_size": 0,
            "error": None
        }
        
        try:
            # 检查文件是否存在
            result["exists"] = video_path.exists()
            if not result["exists"]:
                result["error"] = "文件不存在"
                return result
            
            # 检查是否为文件
            result["is_file"] = video_path.is_file()
            if not result["is_file"]:
                result["error"] = "路径不是文件"
                return result
            
            # 检查文件格式
            supported_formats = self.workflow_manager.get_supported_formats()
            result["supported_format"] = video_path.suffix.lower() in supported_formats
            if not result["supported_format"]:
                result["error"] = f"不支持的格式: {video_path.suffix}"
                return result
            
            # 获取文件大小
            result["file_size"] = video_path.stat().st_size
            
            # 验证通过
            result["valid"] = True
            
        except Exception as e:
            result["error"] = str(e)
        
        return result
    
    def get_supported_formats(self) -> List[str]:
        """获取支持的视频格式"""
        return self.workflow_manager.get_supported_formats()
    
    def get_detector_types(self) -> List[str]:
        """获取支持的检测器类型"""
        return [dt.value for dt in DetectorType]
    
    def get_output_formats(self) -> List[str]:
        """获取支持的输出格式"""
        return [of.value for of in OutputFormat]
    
    def get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            "detector_type": DetectorType.CONTENT.value,
            "threshold": 30.0,
            "min_scene_length": 1.0,
            "output_format": OutputFormat.JSON.value,
            "enable_ai_analysis": False,
            "enable_video_splitting": True,
            "use_advanced_split": True,
            "split_quality": 23,
            "split_preset": "fast",
            "max_video_duration": 60.0,
            "supported_formats": self.get_supported_formats(),
            "detector_types": self.get_detector_types(),
            "output_formats": self.get_output_formats()
        }
