"""
Video file validator for service reviews.
Validates file size, type, and duration constraints.
"""

from typing import BinaryIO, List
from rest_framework import serializers


class VideoValidator:
    """
    Validates video files before upload.
    Checks size, type, and duration constraints.
    """
    
    def __init__(
        self,
        max_size_bytes: int = 100 * 1024 * 1024,  # 100MB default
        allowed_types: List[str] = None,
        max_duration_seconds: int = 300  # 5 minutes default
    ):
        """
        Initialize video validator with configurable limits.
        
        Args:
            max_size_bytes: Maximum file size in bytes (default: 100MB)
            allowed_types: List of allowed MIME types (default: MP4, MOV, WebM)
            max_duration_seconds: Maximum video duration in seconds (default: 300s/5min)
        """
        self.max_size_bytes = max_size_bytes
        self.allowed_types = allowed_types or [
            'video/mp4',
            'video/quicktime',  # MOV
            'video/webm'
        ]
        self.max_duration_seconds = max_duration_seconds
    
    def validate(self, file: BinaryIO) -> None:
        """
        Run all validation checks on the video file.
        
        Args:
            file: Video file binary stream
            
        Raises:
            serializers.ValidationError: If any validation check fails
        """
        self._validate_size(file)
        self._validate_type(file)
        self._validate_duration(file)
    
    def _validate_size(self, file: BinaryIO) -> None:
        """
        Check if file size is within the allowed limit.
        
        Args:
            file: Video file binary stream
            
        Raises:
            serializers.ValidationError: If file size exceeds limit
        """
        # Get file size by seeking to end
        file.seek(0, 2)  # Seek to end
        file_size = file.tell()
        file.seek(0)  # Reset to beginning
        
        if file_size > self.max_size_bytes:
            max_mb = self.max_size_bytes / (1024 * 1024)
            actual_mb = file_size / (1024 * 1024)
            raise serializers.ValidationError(
                f"Video file too large. Maximum size is {max_mb:.0f}MB, "
                f"but uploaded file is {actual_mb:.1f}MB."
            )
    
    def _validate_type(self, file: BinaryIO) -> None:
        """
        Check if file MIME type is in the allowed list.
        
        Args:
            file: Video file binary stream
            
        Raises:
            serializers.ValidationError: If file type is not allowed
        """
        content_type = getattr(file, 'content_type', None)
        
        if content_type and content_type not in self.allowed_types:
            allowed_formats = ', '.join([
                'MP4' if t == 'video/mp4' else
                'MOV' if t == 'video/quicktime' else
                'WebM' if t == 'video/webm' else t
                for t in self.allowed_types
            ])
            raise serializers.ValidationError(
                f"Invalid video format. Allowed formats: {allowed_formats}."
            )
    
    def _validate_duration(self, file: BinaryIO) -> None:
        """
        Validate video duration (placeholder for client-side validation).
        
        Note: Accurate duration validation happens on Cloudinary after upload.
        This method is a placeholder for future client-side duration checks.
        
        Args:
            file: Video file binary stream
        """
        # Detailed duration check happens on Cloudinary
        # This is a placeholder for client-side validation
        pass
