#!/usr/bin/env python3
"""
视频场景检测器实现
"""

from contextlib import contextmanager
from typing import List

from scenedetect import VideoManager, SceneManager
from scenedetect.detectors import ContentDetector, ThresholdDetector

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

class PySceneDetectDetector:
    """PySceneDetect场景检测器实现"""

    def __init__(self):
        logger.info("PySceneDetect detector initialized")
    
    @contextmanager
    def _video_manager(self, video_path: str):
        """视频管理器上下文管理器"""
        video_manager = VideoManager([video_path])
        try:
            video_manager.start()
            yield video_manager
        finally:
            video_manager.release()
    
    def detect_scenes(self, video_path: str, config: DetectionConfig) -> List[SceneInfo]:
        """检测场景"""
        logger.info(f"Detecting scenes: {video_path}, threshold: {config.threshold}")
        
        with self._video_manager(video_path) as video_manager:
            scene_manager = SceneManager()
            
            # 添加检测器
            if config.detector_type == DetectorType.CONTENT:
                scene_manager.add_detector(ContentDetector(threshold=config.threshold))
            else:
                scene_manager.add_detector(ThresholdDetector(threshold=config.threshold))
            
            # 执行检测
            scene_manager.detect_scenes(frame_source=video_manager)
            scene_list = scene_manager.get_scene_list()
            
            # 转换结果
            scenes = self._convert_scenes(scene_list, config)
            
            if not scenes:
                # 创建单个场景
                scenes = self._create_single_scene(video_manager)
            
            logger.info(f"Detected {len(scenes)} scenes")
            return scenes
    
    def _convert_scenes(self, scene_list: List, config: DetectionConfig) -> List[SceneInfo]:
        """转换场景列表"""
        scenes = []
        for i, (start_time, end_time) in enumerate(scene_list):
            duration = end_time.get_seconds() - start_time.get_seconds()
            
            # 过滤太短的场景
            if duration < config.min_scene_length:
                logger.debug(f"Skipping short scene {i+1}: {duration:.2f}s")
                continue
            
            scene_info = SceneInfo(
                scene_number=len(scenes) + 1,  # 重新编号
                start_time=start_time.get_seconds(),
                end_time=end_time.get_seconds(),
                duration=duration,
                start_frame=start_time.get_frames(),
                end_frame=end_time.get_frames()
            )
            scenes.append(scene_info)
        
        return scenes
    
    def _create_single_scene(self, video_manager) -> List[SceneInfo]:
        """创建单个场景"""
        try:
            duration_info = video_manager.get_duration()
            fps = video_manager.get_framerate()
            
            if isinstance(duration_info, tuple):
                total_frames, fps = duration_info
                total_duration = total_frames / fps if fps > 0 else 0
            else:
                total_duration = duration_info.get_seconds() if hasattr(duration_info, 'get_seconds') else float(duration_info)
                total_frames = int(total_duration * fps) if fps > 0 else 0
            
            return [SceneInfo(
                scene_number=1,
                start_time=0.0,
                end_time=total_duration,
                duration=total_duration,
                start_frame=0,
                end_frame=total_frames
            )]
        except Exception as e:
            logger.warning(f"Failed to create single scene: {e}")
            return []
