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

import time
from pathlib import Path
from typing import Dict, Any, Optional, 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


class SceneDetectionWorkflowManager:
    """场景检测工作流管理器"""
    
    def __init__(self):
        self.nodes = WorkflowNodes()
        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
