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

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


@dataclass
class BatchVideoTask:
    """批量视频处理任务"""
    video_path: Path
    output_dir: Optional[Path] = None
    status: str = "pending"  # pending, processing, completed, failed
    detection_result: Optional[DetectionResult] = None
    split_results: List[Dict[str, Any]] = field(default_factory=list)
    error: Optional[str] = None
    start_time: Optional[float] = None
    end_time: Optional[float] = None


@dataclass
class BatchSceneDetectionWorkflowState:
    """批量场景检测工作流状态"""
    # 输入参数
    video_paths: List[Path] = field(default_factory=list)
    output_base_dir: Optional[Path] = None
    detector_type: str = "content"
    threshold: float = 30.0
    min_scene_length: float = 1.0
    output_format: str = "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 = 2.0  # 最大视频时长（秒），默认60秒

    # 批量处理配置
    max_concurrent: int = 4
    continue_on_error: bool = True
    
    # 工作流状态
    current_stage: str = "init"
    current_task_index: int = 0
    total_tasks: int = 0
    completed_tasks: int = 0
    failed_tasks: int = 0
    
    # JSON-RPC支持
    request_id: Optional[str] = None
    enable_jsonrpc: bool = False
    
    # 任务列表
    tasks: List[BatchVideoTask] = field(default_factory=list)
    
    # 全局结果
    batch_results: Dict[str, Any] = field(default_factory=dict)
    global_errors: List[str] = field(default_factory=list)

    def __post_init__(self):
        if not self.tasks and self.video_paths:
            # 从视频路径创建任务
            self.tasks = [
                BatchVideoTask(
                    video_path=video_path,
                    output_dir=self.output_base_dir / video_path.stem if self.output_base_dir else None
                )
                for video_path in self.video_paths
            ]
            self.total_tasks = len(self.tasks)
    
    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:
            # 计算总体进度
            if self.total_tasks > 0:
                progress_percent = int((self.completed_tasks / self.total_tasks * 100))
            else:
                progress_percent = -1
            
            # 添加批量处理特定数据
            progress_data = {
                "current_task": self.current_task_index + 1,
                "total_tasks": self.total_tasks,
                "completed_tasks": self.completed_tasks,
                "failed_tasks": self.failed_tasks,
                "current_stage": self.current_stage
            }
            
            if data:
                progress_data.update(data)
            
            handler.progress(step, progress_percent, message, level, progress_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)
    
    def get_current_task(self) -> Optional[BatchVideoTask]:
        """获取当前任务"""
        if 0 <= self.current_task_index < len(self.tasks):
            return self.tasks[self.current_task_index]
        return None
    
    def mark_task_completed(self, task_index: int, result: DetectionResult, split_results: List[Dict[str, Any]] = None):
        """标记任务完成"""
        if 0 <= task_index < len(self.tasks):
            task = self.tasks[task_index]
            task.status = "completed"
            task.detection_result = result
            task.split_results = split_results or []
            self.completed_tasks += 1
    
    def mark_task_failed(self, task_index: int, error: str):
        """标记任务失败"""
        if 0 <= task_index < len(self.tasks):
            task = self.tasks[task_index]
            task.status = "failed"
            task.error = error
            self.failed_tasks += 1
    
    def get_summary(self) -> Dict[str, Any]:
        """获取批量处理摘要"""
        return {
            "total_tasks": self.total_tasks,
            "completed_tasks": self.completed_tasks,
            "failed_tasks": self.failed_tasks,
            "success_rate": (self.completed_tasks / self.total_tasks * 100) if self.total_tasks > 0 else 0,
            "current_stage": self.current_stage,
            "tasks": [
                {
                    "video_path": str(task.video_path),
                    "status": task.status,
                    "total_scenes": task.detection_result.total_scenes if task.detection_result else 0,
                    "split_count": len(task.split_results),
                    "error": task.error
                }
                for task in self.tasks
            ]
        }
