import os
from typing import Any, Dict, List
from sqlalchemy.orm import Session
from models.settings import SystemSettings

class SettingsService:
    """Service for managing system settings."""
    
    @staticmethod
    def get_setting(db: Session, key: str, default: Any = None) -> Any:
        """Get a setting value by key, return default if not found."""
        setting = db.query(SystemSettings).filter(SystemSettings.key == key).first()
        if not setting:
            return default
            
        # Convert value based on expected type (basic handling)
        if isinstance(default, int):
            try:
                return int(setting.value)
            except ValueError:
                return default
        elif isinstance(default, bool):
            return setting.value.lower() == "true"
        elif isinstance(default, list):
            return setting.value.split(",")
            
        return setting.value
    
    @staticmethod
    def set_setting(db: Session, key: str, value: str, description: str = None, category: str = "general") -> SystemSettings:
        """Set a setting value."""
        setting = db.query(SystemSettings).filter(SystemSettings.key == key).first()
        if setting:
            setting.value = str(value)
            if description:
                setting.description = description
            if category:
                setting.category = category
        else:
            setting = SystemSettings(
                key=key, 
                value=str(value), 
                description=description, 
                category=category
            )
            db.add(setting)
        
        db.commit()
        db.refresh(setting)
        return setting
    
    @staticmethod
    def get_upload_limits(db: Session) -> Dict[str, Any]:
        """Get all upload-related settings."""
        return {
            "max_album_size_mb": SettingsService.get_setting(db, "max_album_size_mb", 100),
            "max_vlog_size_mb": SettingsService.get_setting(db, "max_vlog_size_mb", 500),
            "max_image_size_mb": SettingsService.get_setting(db, "max_image_size_mb", 10),
            "max_video_size_mb": SettingsService.get_setting(db, "max_video_size_mb", 100),
            "allowed_image_types": SettingsService.get_setting(db, "allowed_image_types", 
                ["image/jpeg", "image/png", "image/gif", "image/webp"]),
            "allowed_video_types": SettingsService.get_setting(db, "allowed_video_types", 
                ["video/mp4", "video/mpeg", "video/quicktime", "video/webm"])
        }
    
    @staticmethod
    def get_max_upload_size(db: Session, content_type: str, is_vlog: bool = False) -> int:
        """Get max upload size for a specific content type."""
        if content_type.startswith('image/'):
            max_size_mb = SettingsService.get_setting(db, "max_image_size_mb", 10)
            max_size_bytes = max_size_mb * 1024 * 1024
            print(f"DEBUG - Image upload limit: {max_size_mb}MB = {max_size_bytes} bytes")
            return max_size_bytes
        elif content_type.startswith('video/'):
            if is_vlog:
                max_size_mb = SettingsService.get_setting(db, "max_vlog_size_mb", 500)
                print(f"DEBUG - Vlog upload limit: {max_size_mb}MB")
            else:
                max_size_mb = SettingsService.get_setting(db, "max_video_size_mb", 100)
                print(f"DEBUG - Video upload limit: {max_size_mb}MB")
            
            max_size_bytes = max_size_mb * 1024 * 1024
            return max_size_bytes
        else:
            default_size = 10 * 1024 * 1024  # 10MB par défaut
            print(f"DEBUG - Default upload limit: 10MB = {default_size} bytes")
            return default_size
    
    @staticmethod
    def is_file_type_allowed(db: Session, content_type: str) -> bool:
        """Check if file type is allowed."""
        if content_type.startswith('image/'):
            allowed = SettingsService.get_setting(db, "allowed_image_types", 
                ["image/jpeg", "image/png", "image/gif", "image/webp"])
            if isinstance(allowed, str):
                allowed = allowed.split(",")
            return content_type in allowed
        elif content_type.startswith('video/'):
            allowed = SettingsService.get_setting(db, "allowed_video_types", 
                ["video/mp4", "video/mpeg", "video/quicktime", "video/webm"])
            if isinstance(allowed, str):
                allowed = allowed.split(",")
            return content_type in allowed
        return False
