#!/usr/bin/env python3
"""
Workflow Manager
工作流管理器
"""

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

from python_core.utils.logger import logger
from python_core.utils.jsonrpc_enhanced import EnhancedJSONRPCResponse
from ..types import SceneDetectionWorkflowState, DetectorType, OutputFormat
from .workflow_nodes import WorkflowNodes
from .batch_workflow_nodes import BatchWorkflowNodes
from ..types.batch_workflow_state import BatchSceneDetectionWorkflowState


class SceneDetectionWorkflowManager:
    """场景检测工作流管理器"""
    
    def __init__(self):
        self.nodes = WorkflowNodes()
        self.batch_nodes = BatchWorkflowNodes()
        self.workflow = None
    
    def create_detection_workflow(self):
        """创建检测工作流"""
        try:
            from langgraph.graph import StateGraph, END
            
            # 创建状态图
            workflow = StateGraph(SceneDetectionWorkflowState)
            
            # 添加节点
            workflow.add_node("validate", self.nodes.validate_input)
            workflow.add_node("extract_info", self.nodes.extract_video_info)
            workflow.add_node("detect", self.nodes.detect_scenes)
            workflow.add_node("analyze", self.nodes.analyze_with_ai)
            workflow.add_node("finalize", self.nodes.finalize_results)
            workflow.add_node("error", self.nodes.handle_error)
            
            # 设置入口点
            workflow.set_entry_point("validate")
            
            # 添加条件边
            workflow.add_conditional_edges(
                "validate",
                self._route_next_step,
                {
                    "extract_info": "extract_info",
                    "error": "error"
                }
            )
            
            workflow.add_conditional_edges(
                "extract_info",
                self._route_next_step,
                {
                    "detect": "detect",
                    "error": "error"
                }
            )
            
            workflow.add_conditional_edges(
                "detect",
                self._route_next_step,
                {
                    "analyze": "analyze",
                    "error": "error"
                }
            )
            
            workflow.add_conditional_edges(
                "analyze",
                self._route_next_step,
                {
                    "finalize": "finalize",
                    "error": "error"
                }
            )
            
            # 结束节点
            workflow.add_edge("finalize", END)
            workflow.add_edge("error", END)
            
            # 编译工作流
            self.workflow = workflow.compile()
            return self.workflow
            
        except ImportError:
            logger.error("❌ LangGraph未安装，无法创建工作流")
            return None
        except Exception as e:
            logger.error(f"❌ 创建工作流失败: {e}")
            return None
    
    def _route_next_step(self, state: SceneDetectionWorkflowState) -> Literal["extract_info", "detect", "analyze", "finalize", "error"]:
        """路由下一步"""
        if state.errors:
            return "error"
        elif state.current_stage == "validated":
            return "extract_info"
        elif state.current_stage == "info_extracted":
            return "detect"
        elif state.current_stage == "scenes_detected":
            return "analyze"
        elif state.current_stage in ["ai_analyzed", "analysis_skipped", "analysis_failed"]:
            return "finalize"
        else:
            return "error"
    
    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工作流进行场景检测"""

        # 创建工作流
        workflow = self.create_detection_workflow()
        if not workflow:
            raise Exception("无法创建工作流")

        # 初始化状态
        initial_state = SceneDetectionWorkflowState(
            video_path=str(video_path),
            detector_type=detector_type.value,
            threshold=threshold,
            min_scene_length=min_scene_length,
            output_path=str(output_path) if output_path else None,
            output_format=output_format.value,
            enable_ai_analysis=enable_ai_analysis,
            request_id=request_id,
            enable_jsonrpc=request_id is not None  # 如果有request_id就启用JSON-RPC
        )

        # 执行工作流
        config = {"configurable": {"thread_id": f"detection_{int(time.time())}"}}

        try:
            final_state = workflow.invoke(initial_state, config)
            
            # 如果是JSON-RPC模式，结果已经通过JSON-RPC发送了
            if request_id is not None:
                # JSON-RPC模式：结果已经在工作流节点中发送
                # 这里返回简化的状态信息供内部使用
                return {
                    "jsonrpc_mode": True,
                    "request_id": request_id,
                    "workflow_state": final_state.get("current_stage"),
                    "final_result_sent": True
                }
            else:
                # 非JSON-RPC模式：返回完整结果
                return {
                    "detection_result": final_state.get("detection_result"),
                    "ai_analysis": final_state.get("ai_analysis"),
                    "video_info": final_state.get("video_info"),
                    "workflow_state": final_state.get("current_stage"),
                    "errors": final_state.get("errors", [])
                }

        except Exception as e:
            error_msg = f"工作流执行失败: {e}"
            
            # 如果是JSON-RPC模式，发送错误响应
            if request_id is not None:
                handler = EnhancedJSONRPCResponse(request_id)
                handler.error(-32603, error_msg, {"exception": str(e)})
                return {
                    "jsonrpc_mode": True,
                    "request_id": request_id,
                    "error_sent": True,
                    "error": error_msg
                }
            else:
                # 非JSON-RPC模式：抛出异常
                logger.error(f"❌ {error_msg}")
                raise

    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]:
        """批量场景检测和视频切分"""

        # 创建批量工作流状态
        state = BatchSceneDetectionWorkflowState(
            video_paths=video_paths,
            output_base_dir=output_base_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,
            max_concurrent=max_concurrent,
            continue_on_error=continue_on_error,
            request_id=request_id,
            enable_jsonrpc=request_id is not None
        )

        try:
            logger.info(f"🚀 开始批量场景检测和切分")
            logger.info(f"📁 视频数量: {len(video_paths)}")
            logger.info(f"📂 输出目录: {output_base_dir}")
            logger.info(f"🎯 检测器: {detector_type.value}, 阈值: {threshold}")
            logger.info(f"✂️ 视频切分: {'启用' if enable_video_splitting else '禁用'}")
            logger.info(f"🔄 并发数: {max_concurrent}")

            # 1. 验证输入
            validation_result = self.batch_nodes.validate_batch_input(state)
            if validation_result["workflow_state"] == "failed":
                error_msg = f"批量输入验证失败: {'; '.join(validation_result['errors'])}"
                if request_id:
                    state.send_error_result(-32602, error_msg, validation_result["errors"])
                    return {
                        "jsonrpc_mode": True,
                        "request_id": request_id,
                        "error_sent": True,
                        "error": error_msg
                    }
                else:
                    raise ValueError(error_msg)

            # 2. 批量处理
            processing_result = self.batch_nodes.process_videos_batch(state)

            # 3. 构建最终结果
            final_result = {
                "workflow_state": processing_result["workflow_state"],
                "summary": processing_result["summary"],
                "batch_results": {
                    "total_videos": state.total_tasks,
                    "completed_videos": state.completed_tasks,
                    "failed_videos": state.failed_tasks,
                    "success_rate": (state.completed_tasks / state.total_tasks * 100) if state.total_tasks > 0 else 0,
                    "output_base_dir": str(output_base_dir) if output_base_dir else None,
                    "enable_video_splitting": enable_video_splitting,
                    "tasks": [
                        {
                            "video_path": str(task.video_path),
                            "status": task.status,
                            "output_dir": str(task.output_dir) if task.output_dir else None,
                            "total_scenes": task.detection_result.total_scenes if task.detection_result else 0,
                            "detection_time": task.detection_result.detection_time if task.detection_result else 0,
                            "split_count": len(task.split_results) if task.split_results else 0,
                            "error": task.error,
                            "processing_time": (task.end_time - task.start_time) if task.start_time and task.end_time else 0
                        }
                        for task in state.tasks
                    ]
                }
            }

            if request_id:
                state.send_final_result(final_result)
                return {
                    "jsonrpc_mode": True,
                    "request_id": request_id,
                    "result_sent": True,
                    "result": final_result
                }
            else:
                return final_result

        except Exception as e:
            error_msg = f"批量工作流执行失败: {str(e)}"
            logger.error(error_msg)

            if request_id:
                state.send_error_result(-32603, error_msg, str(e))
                return {
                    "jsonrpc_mode": True,
                    "request_id": request_id,
                    "error_sent": True,
                    "error": error_msg
                }
            else:
                logger.error(f"❌ {error_msg}")
                raise
