#!/usr/bin/env python3
"""
Workflow State
工作流状态定义
"""

from dataclasses import dataclass
from typing import Dict, Any, List, Optional
from .models import SceneInfo, DetectionResult
from python_core.utils.jsonrpc_enhanced import EnhancedJSONRPCResponse, ProgressLevel


@dataclass
class SceneDetectionWorkflowState:
    """场景检测工作流状态"""
    # 输入参数
    video_path: str = ""
    detector_type: str = "content"
    threshold: float = 30.0
    min_scene_length: float = 1.0
    output_path: Optional[str] = None
    output_format: str = "json"
    enable_ai_analysis: bool = True

    # 工作流状态
    current_stage: str = "init"
    progress: int = 0
    total_steps: int = 5
    
    # JSON-RPC支持
    request_id: Optional[str] = None
    enable_jsonrpc: bool = False

    # 中间结果
    video_info: Dict[str, Any] = None
    raw_scenes: List[Any] = None
    processed_scenes: List[SceneInfo] = None

    # 最终结果
    detection_result: Optional[DetectionResult] = None
    ai_analysis: Optional[str] = None

    # 错误处理
    errors: List[str] = None

    def __post_init__(self):
        if self.video_info is None:
            self.video_info = {}
        if self.raw_scenes is None:
            self.raw_scenes = []
        if self.processed_scenes is None:
            self.processed_scenes = []
        if self.errors is None:
            self.errors = []
    
    def get_jsonrpc_handler(self) -> Optional[EnhancedJSONRPCResponse]:
        """获取JSON-RPC响应处理器"""
        if self.enable_jsonrpc and self.request_id:
            return EnhancedJSONRPCResponse(self.request_id)
        return None

    def send_progress(self, step: str, message: str, level: ProgressLevel = ProgressLevel.INFO,
                     data: Optional[Dict[str, Any]] = None) -> None:
        """发送进度更新"""
        handler = self.get_jsonrpc_handler()
        if handler:
            progress_percent = int((self.progress / self.total_steps * 100)) if self.total_steps > 0 else -1
            handler.progress(step, progress_percent, message, level, data)
    
    def send_final_result(self, result: Dict[str, Any]) -> None:
        """发送最终结果"""
        handler = self.get_jsonrpc_handler()
        if handler:
            # 发送最终结果作为成功响应
            handler.success(result)
        
    def send_error_result(self, error_code: int, error_message: str, error_data: Any = None) -> None:
        """发送错误结果"""
        handler = self.get_jsonrpc_handler()
        if handler:
            # 发送错误响应
            handler.error(error_code, error_message, error_data)
