#!/usr/bin/env python3
"""
视频拆分服务的类型定义和数据结构
"""

from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Dict, Optional, Protocol, Union, Any
from dataclasses import dataclass, asdict, field
from datetime import datetime
from enum import Enum

# 类型定义
class DetectorType(Enum):
    """检测器类型枚举"""
    CONTENT = "content"
    THRESHOLD = "threshold"

class ServiceError(Exception):
    """服务基础异常"""
    def __init__(self, message: str, error_code: str = "UNKNOWN_ERROR"):
        super().__init__(message)
        self.error_code = error_code
        self.message = message

class DependencyError(ServiceError):
    """依赖缺失异常"""
    def __init__(self, dependency: str):
        super().__init__(f"Required dependency not available: {dependency}", "DEPENDENCY_ERROR")

class ValidationError(ServiceError):
    """验证错误异常"""
    def __init__(self, message: str):
        super().__init__(message, "VALIDATION_ERROR")

@dataclass(frozen=True)
class SceneInfo:
    """场景信息 - 不可变数据类"""
    scene_number: int
    start_time: float
    end_time: float
    duration: float
    start_frame: int
    end_frame: int
    
    def __post_init__(self):
        """数据验证"""
        if self.scene_number <= 0:
            raise ValidationError("Scene number must be positive")
        if self.start_time < 0 or self.end_time < 0:
            raise ValidationError("Time values must be non-negative")
        if self.start_time >= self.end_time:
            raise ValidationError("Start time must be less than end time")
        if abs(self.duration - (self.end_time - self.start_time)) > 0.01:
            raise ValidationError("Duration must match time difference")

@dataclass
class AnalysisResult:
    """分析结果"""
    success: bool
    video_path: str
    total_scenes: int = 0
    total_duration: float = 0.0
    average_scene_duration: float = 0.0
    scenes: List[SceneInfo] = field(default_factory=list)
    analysis_time: float = 0.0
    error: Optional[str] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        result = asdict(self)
        result['scenes'] = [asdict(scene) for scene in self.scenes]
        return result

@dataclass
class DetectionConfig:
    """检测配置"""
    threshold: float = 30.0
    detector_type: DetectorType = DetectorType.CONTENT
    min_scene_length: float = 1.0  # 最小场景长度（秒）
    
    def __post_init__(self):
        """配置验证"""
        if not 0 < self.threshold <= 100:
            raise ValidationError("Threshold must be between 0 and 100")
        if self.min_scene_length < 0:
            raise ValidationError("Minimum scene length must be non-negative")

# 协议定义
class SceneDetector(Protocol):
    """场景检测器协议"""
    def detect_scenes(self, video_path: str, config: DetectionConfig) -> List[SceneInfo]:
        """检测场景"""
        ...

class VideoValidator(Protocol):
    """视频验证器协议"""
    def validate(self, video_path: str) -> bool:
        """验证视频文件"""
        ...
