"""
单个文件场景检测工作流管理器
"""

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

from python_core.utils.logger import logger
from .single_workflow_nodes import SingleWorkflowNodes
from ..types.single_workflow_state import SingleSceneDetectionWorkflowState
from ..types.enums import DetectorType, OutputFormat


class SingleWorkflowManager:
    """单个文件场景检测工作流管理器"""
    
    def __init__(self):
        self.workflow_nodes = SingleWorkflowNodes()
    
    def detect_and_split_single_video(
        self,
        video_path: Path,
        output_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,
        use_advanced_split: bool = True,
        split_quality: int = 23,
        split_preset: str = "fast",
        max_video_duration: float = 60.0,
        project_id: Optional[str] = None,
        project_directory: Optional[Path] = None,
        material_tags: Optional[List[str]] = None,
        request_id: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        单个视频文件的场景检测和切分
        
        Args:
            video_path: 视频文件路径
            output_dir: 输出目录
            detector_type: 检测器类型
            threshold: 检测阈值
            min_scene_length: 最小场景长度
            output_format: 输出格式
            enable_ai_analysis: 是否启用AI分析
            enable_video_splitting: 是否启用视频切分
            use_advanced_split: 是否使用高级切分
            split_quality: 切分质量
            split_preset: 切分预设
            max_video_duration: 最大视频时长
            project_id: 项目ID（用于项目素材导入）
            project_directory: 项目目录（用于项目素材导入）
            material_tags: 素材标签
            request_id: 请求ID（用于JSON-RPC进度报告）
            
        Returns:
            Dict: 处理结果
        """
        
        # 验证输入
        if not video_path.exists():
            raise FileNotFoundError(f"视频文件不存在: {video_path}")
        
        if not video_path.suffix.lower() in {'.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm', '.m4v'}:
            raise ValueError(f"不支持的视频格式: {video_path.suffix}")
        
        # 设置默认输出目录
        if output_dir is None:
            output_dir = video_path.parent / f"{video_path.stem}_scenes"
        
        # 确保输出目录存在
        output_dir.mkdir(parents=True, exist_ok=True)
        
        logger.info(f"🚀 开始单个视频场景检测和切分")
        logger.info(f"📁 视频文件: {video_path}")
        logger.info(f"📂 输出目录: {output_dir}")
        logger.info(f"🎯 检测器: {detector_type.value}, 阈值: {threshold}")
        logger.info(f"✂️ 视频切分: {'启用' if enable_video_splitting else '禁用'}")
        
        if project_id:
            logger.info(f"📦 项目导入: {project_id}")
        
        # 创建工作流状态
        state = SingleSceneDetectionWorkflowState(
            video_path=video_path,
            output_dir=output_dir,
            detector_type=detector_type.value,
            threshold=threshold,
            min_scene_length=min_scene_length,
            output_format=output_format.value,
            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,
            project_id=project_id,
            project_directory=project_directory,
            material_tags=material_tags or [],
            request_id=request_id,
            enable_jsonrpc=request_id is not None
        )
        
        try:
            # 执行工作流
            result = self.workflow_nodes.process_single_video(state)
            
            # 构建返回结果
            response = {
                "success": result["success"],
                "video_path": str(video_path),
                "output_dir": str(output_dir),
                "processing_time": result.get("processing_time", 0),
                "total_scenes": result.get("total_scenes", 0),
                "total_segments": result.get("total_segments", 0),
                "state": state.to_dict()
            }
            
            if result["success"]:
                # 转换检测结果为字典
                detection_result_dict = None
                if result.get("detection_result"):
                    from dataclasses import asdict
                    detection_result_dict = asdict(result["detection_result"])

                response.update({
                    "detection_result": detection_result_dict,
                    "split_results": [
                        {
                            "scene_index": sr.scene_index,
                            "output_path": str(sr.output_path),
                            "start_time": sr.start_time,
                            "end_time": sr.end_time,
                            "duration": sr.duration,
                            "file_size": sr.file_size,
                            "success": sr.success,
                            "error": sr.error
                        }
                        for sr in result.get("split_results", [])
                    ]
                })
                
                logger.info(f"✅ 单个视频处理成功!")
                logger.info(f"📊 处理统计:")
                logger.info(f"   视频文件: {video_path.name}")
                logger.info(f"   处理时间: {result.get('processing_time', 0):.1f}s")
                logger.info(f"   场景数量: {result.get('total_scenes', 0)}")
                logger.info(f"   切分片段: {result.get('total_segments', 0)}")
                
            else:
                response["error"] = result.get("error", "未知错误")
                logger.error(f"❌ 单个视频处理失败: {response['error']}")
            
            return response
            
        except Exception as e:
            error_msg = f"工作流执行失败: {str(e)}"
            logger.error(f"❌ {error_msg}")
            
            return {
                "success": False,
                "error": error_msg,
                "video_path": str(video_path),
                "output_dir": str(output_dir),
                "processing_time": state.processing_time or 0,
                "state": state.to_dict()
            }
    
    def detect_and_split_for_project(
        self,
        video_path: Path,
        project_id: str,
        project_directory: 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: 素材标签
            其他参数: 检测和切分配置
            
        Returns:
            Dict: 处理结果
        """
        
        # 创建临时输出目录
        temp_output_dir = project_directory / "temp" / f"{video_path.stem}_processing"
        
        return self.detect_and_split_single_video(
            video_path=video_path,
            output_dir=temp_output_dir,
            detector_type=detector_type,
            threshold=threshold,
            min_scene_length=min_scene_length,
            output_format=OutputFormat.JSON,
            enable_ai_analysis=False,
            enable_video_splitting=True,
            use_advanced_split=True,
            split_quality=split_quality,
            split_preset=split_preset,
            max_video_duration=max_video_duration,
            project_id=project_id,
            project_directory=project_directory,
            material_tags=material_tags,
            request_id=request_id
        )
    
    def get_supported_formats(self) -> List[str]:
        """获取支持的视频格式"""
        return ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm', '.m4v']
    
    def validate_video_file(self, video_path: Path) -> bool:
        """验证视频文件"""
        if not video_path.exists():
            return False
        
        if not video_path.is_file():
            return False
        
        if video_path.suffix.lower() not in self.get_supported_formats():
            return False
        
        return True
