#!/usr/bin/env python3
"""
Scene Detector Service
场景检测服务
"""

import time
from pathlib import Path
from typing import List, Set

from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector, ThresholdDetector, AdaptiveDetector

from python_core.utils.logger import logger
from ..types import DetectorType, SceneInfo, DetectionResult


def _timecode_to_seconds(timecode) -> float:
    """将FrameTimecode对象转换为秒数"""
    try:
        # 新版本PySceneDetect
        if hasattr(timecode, 'total_seconds'):
            return timecode.total_seconds()
        # 旧版本PySceneDetect
        elif hasattr(timecode, 'get_seconds'):
            return timecode.get_seconds()
        # 如果是数字，直接返回
        elif isinstance(timecode, (int, float)):
            return float(timecode)
        # 尝试直接转换
        else:
            return float(timecode)
    except Exception as e:
        logger.warning(f"时间码转换失败: {e}, 使用默认值0.0")
        return 0.0


class SceneDetectorService:
    """场景检测服务"""
    
    def __init__(self):
        self.supported_formats: Set[str] = {
            '.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm', '.m4v'
        }
    
    def detect_scenes(self, video_path: Path, detector_type: DetectorType = DetectorType.CONTENT,
                     threshold: float = 30.0, min_scene_length: float = 1.0) -> DetectionResult:
        """检测视频场景"""
        detection_start_time = time.time()
        
        try:
            logger.info(f"🎬 开始检测: {video_path.name}")
            
            # 打开视频
            video = open_video(str(video_path))
            scene_manager = SceneManager()
            
            # 选择检测器
            detector = self._create_detector(detector_type, threshold)
            scene_manager.add_detector(detector)
            
            logger.info(f"📊 使用{detector_type.value}检测器，阈值: {threshold}")
            
            # 执行检测
            logger.info("🔍 正在分析视频帧...")
            scene_manager.detect_scenes(video, show_progress=False)
            
            # 获取场景列表
            scene_list = scene_manager.get_scene_list()
            
            # 过滤短场景
            if min_scene_length > 0:
                filtered_scenes = []
                for scene in scene_list:
                    start_time, end_time = scene
                    start_seconds = _timecode_to_seconds(start_time)
                    end_seconds = _timecode_to_seconds(end_time)
                    duration = end_seconds - start_seconds

                    if duration >= min_scene_length:
                        filtered_scenes.append(scene)
                scene_list = filtered_scenes
            
            # 转换为SceneInfo对象
            scenes = self._convert_scenes(scene_list, video.frame_rate)
            
            detection_time = time.time() - detection_start_time
            total_duration = _timecode_to_seconds(video.duration)
            
            logger.info(f"✅ 检测到 {len(scenes)} 个场景")
            logger.info(f"📊 视频信息: {video.frame_rate:.2f}fps, {total_duration:.2f}秒")
            logger.info(f"🎯 检测完成: {len(scenes)} 个场景，耗时 {detection_time:.2f}秒")
            
            return DetectionResult(
                success=True,
                filename=video_path.name,
                detector_type=detector_type,
                threshold=threshold,
                total_scenes=len(scenes),
                total_duration=total_duration,
                detection_time=detection_time,
                scenes=scenes
            )
            
        except Exception as e:
            detection_time = time.time() - detection_start_time
            error_msg = f"场景检测失败: {str(e)}"
            logger.error(error_msg)
            logger.error(f"详细错误信息: {type(e).__name__}: {e}")
            import traceback
            logger.error(f"错误堆栈: {traceback.format_exc()}")
            
            return DetectionResult(
                success=False,
                filename=video_path.name,
                detector_type=detector_type,
                threshold=threshold,
                total_scenes=0,
                total_duration=0,
                detection_time=detection_time,
                scenes=[],
                error=error_msg
            )
    
    def _create_detector(self, detector_type: DetectorType, threshold: float):
        """创建检测器"""
        if detector_type == DetectorType.CONTENT:
            return ContentDetector(threshold=threshold)
        elif detector_type == DetectorType.THRESHOLD:
            return ThresholdDetector(threshold=threshold)
        elif detector_type == DetectorType.ADAPTIVE:
            return AdaptiveDetector()
        else:
            raise ValueError(f"不支持的检测器类型: {detector_type}")
    
    def _convert_scenes(self, scene_list, frame_rate: float) -> List[SceneInfo]:
        """转换场景列表为SceneInfo对象"""
        scenes = []

        for i, (start_time, end_time) in enumerate(scene_list):
            start_seconds = _timecode_to_seconds(start_time)
            end_seconds = _timecode_to_seconds(end_time)
            duration = end_seconds - start_seconds

            start_frame = int(start_seconds * frame_rate)
            end_frame = int(end_seconds * frame_rate)

            scene_info = SceneInfo(
                index=i,
                start_time=start_seconds,
                end_time=end_seconds,
                duration=duration,
                start_frame=start_frame,
                end_frame=end_frame
            )
            scenes.append(scene_info)

        return scenes
