#!/usr/bin/env python3
"""
视频拆分服务核心实现
"""

from pathlib import Path
from typing import Optional

from .types import SceneDetector, VideoValidator, AnalysisResult, DetectionConfig
from .detectors import PySceneDetectDetector
from .validators import BasicVideoValidator
from python_core.utils.command_utils import PerformanceUtils
from python_core.utils.logger import logger



class VideoSplitterService:
    """高质量的视频拆分服务"""
    
    def __init__(self, 
                 detector: Optional[SceneDetector] = None,
                 validator: Optional[VideoValidator] = None,
                 output_base_dir: Optional[str] = None):
        """
        初始化服务
        
        Args:
            detector: 场景检测器
            validator: 视频验证器
            output_base_dir: 输出基础目录
        """
        self.detector = detector or PySceneDetectDetector()
        self.validator = validator or BasicVideoValidator()
        self.output_base_dir = Path(output_base_dir) if output_base_dir else Path("./video_splits")
        self.output_base_dir.mkdir(parents=True, exist_ok=True)
    
    def analyze_video(self, video_path: str, config: Optional[DetectionConfig] = None) -> AnalysisResult:
        """
        分析视频
        
        Args:
            video_path: 视频路径
            config: 检测配置
            
        Returns:
            分析结果
        """
        config = config or DetectionConfig()
        
        try:
            # 验证输入
            self.validator.validate(video_path)
            
            # 执行检测
            scenes, execution_time = PerformanceUtils.time_operation(
                self.detector.detect_scenes, video_path, config
            )
            
            # 计算统计信息
            total_duration = sum(scene.duration for scene in scenes)
            average_duration = total_duration / len(scenes) if scenes else 0
            
            return AnalysisResult(
                success=True,
                video_path=video_path,
                total_scenes=len(scenes),
                total_duration=total_duration,
                average_scene_duration=average_duration,
                scenes=scenes,
                analysis_time=execution_time
            )
            
        except Exception as e:
            logger.error(f"Video analysis failed: {e}")
            return AnalysisResult(
                success=False,
                video_path=video_path,
                error=str(e)
            )
