#!/usr/bin/env python3
"""
Video Info Service
视频信息服务
"""

import cv2
from pathlib import Path
from typing import Dict, Any

from python_core.utils.logger import logger


class VideoInfoService:
    """视频信息服务"""
    
    def extract_video_info(self, video_path: Path) -> Dict[str, Any]:
        """提取视频信息"""
        try:
            cap = cv2.VideoCapture(str(video_path))
            
            if not cap.isOpened():
                raise Exception("无法打开视频文件")
            
            fps = cap.get(cv2.CAP_PROP_FPS)
            frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            duration = frame_count / fps if fps > 0 else 0
            
            cap.release()
            
            # 获取文件大小
            file_size = video_path.stat().st_size
            
            video_info = {
                "filename": video_path.name,
                "file_path": str(video_path),
                "file_size": file_size,
                "fps": fps,
                "frame_count": frame_count,
                "width": width,
                "height": height,
                "duration": duration,
                "resolution": f"{width}x{height}",
                "format": video_path.suffix.lower()
            }
            
            logger.info(f"📹 视频信息: {video_info['resolution']}, {fps:.2f}fps, {duration:.2f}s")
            
            return video_info
            
        except Exception as e:
            logger.error(f"提取视频信息失败: {e}")
            raise
    
    def validate_video_file(self, video_path: Path, supported_formats: set) -> bool:
        """验证视频文件"""
        if not video_path.exists():
            raise FileNotFoundError(f"视频文件不存在: {video_path}")
        
        if video_path.suffix.lower() not in supported_formats:
            raise ValueError(f"不支持的文件格式: {video_path.suffix}")
        
        return True
