"""
单个文件场景检测工作流状态
"""

from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, List, Dict, Any
from datetime import datetime

from .models import DetectionResult
from python_core.utils.jsonrpc_enhanced import ProgressLevel


@dataclass
class SingleVideoTask:
    """单个视频处理任务"""
    video_path: Path
    output_dir: Optional[Path] = None
    
    # 任务状态
    status: str = "pending"  # pending, processing, completed, failed
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None
    error: Optional[str] = None
    
    # 处理结果
    detection_result: Optional[DetectionResult] = None
    split_results: List[Any] = field(default_factory=list)


@dataclass
class SingleSceneDetectionWorkflowState:
    """单个文件场景检测工作流状态"""
    
    # 基础配置
    video_path: Path
    output_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 = 60.0  # 最大视频时长（秒）
    
    # 项目配置（用于项目素材导入）
    project_id: Optional[str] = None
    project_directory: Optional[Path] = None
    material_tags: List[str] = field(default_factory=list)
    
    # 工作流状态
    task: Optional[SingleVideoTask] = None
    current_step: str = "initialized"
    progress: float = 0.0
    
    # JSON-RPC 支持
    request_id: Optional[str] = None
    enable_jsonrpc: bool = False
    
    def __post_init__(self):
        """初始化后处理"""
        if self.task is None:
            self.task = SingleVideoTask(
                video_path=self.video_path,
                output_dir=self.output_dir
            )
    
    def update_progress(self, step: str, progress: float, message: str = ""):
        """更新进度"""
        self.current_step = step
        self.progress = progress
        
        if self.enable_jsonrpc and self.request_id:
            self.send_progress(step, message, ProgressLevel.INFO, {
                "progress": progress,
                "step": step
            })
    
    def send_progress(self, event_type: str, message: str, level: ProgressLevel, data: Dict[str, Any] = None):
        """发送进度消息（JSON-RPC）"""
        if not self.enable_jsonrpc or not self.request_id:
            return
        
        try:
            from python_core.utils.jsonrpc_enhanced import create_response_handler
            handler = create_response_handler(self.request_id)
            handler.progress(
                step=event_type,
                progress=-1,  # 不确定进度时使用-1
                message=message,
                level=level,
                data=data or {}
            )
        except Exception as e:
            print(f"Failed to send progress: {e}")
    
    def mark_task_started(self):
        """标记任务开始"""
        if self.task:
            self.task.status = "processing"
            self.task.start_time = datetime.now()
    
    def mark_task_completed(self, detection_result: DetectionResult, split_results: List[Any] = None):
        """标记任务完成"""
        if self.task:
            self.task.status = "completed"
            self.task.end_time = datetime.now()
            self.task.detection_result = detection_result
            self.task.split_results = split_results or []
    
    def mark_task_failed(self, error: str):
        """标记任务失败"""
        if self.task:
            self.task.status = "failed"
            self.task.end_time = datetime.now()
            self.task.error = error
    
    @property
    def is_completed(self) -> bool:
        """是否已完成"""
        return self.task and self.task.status == "completed"
    
    @property
    def is_failed(self) -> bool:
        """是否失败"""
        return self.task and self.task.status == "failed"
    
    @property
    def processing_time(self) -> Optional[float]:
        """处理时间（秒）"""
        if not self.task or not self.task.start_time:
            return None
        
        end_time = self.task.end_time or datetime.now()
        return (end_time - self.task.start_time).total_seconds()
    
    @property
    def total_scenes(self) -> int:
        """总场景数"""
        if self.task and self.task.detection_result:
            return self.task.detection_result.total_scenes
        return 0
    
    @property
    def total_split_segments(self) -> int:
        """总切分片段数"""
        if self.task and self.task.split_results:
            return len(self.task.split_results)
        return 0
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "video_path": str(self.video_path),
            "output_dir": str(self.output_dir) if self.output_dir else None,
            "detector_type": self.detector_type,
            "threshold": self.threshold,
            "min_scene_length": self.min_scene_length,
            "output_format": self.output_format,
            "enable_ai_analysis": self.enable_ai_analysis,
            "enable_video_splitting": self.enable_video_splitting,
            "use_advanced_split": self.use_advanced_split,
            "split_quality": self.split_quality,
            "split_preset": self.split_preset,
            "max_video_duration": self.max_video_duration,
            "project_id": self.project_id,
            "project_directory": str(self.project_directory) if self.project_directory else None,
            "material_tags": self.material_tags,
            "current_step": self.current_step,
            "progress": self.progress,
            "task_status": self.task.status if self.task else "pending",
            "processing_time": self.processing_time,
            "total_scenes": self.total_scenes,
            "total_split_segments": self.total_split_segments,
            "request_id": self.request_id
        }
