"""Shared configuration management."""
from pydantic_settings import BaseSettings
from typing import Optional
import os


class Settings(BaseSettings):
    """Application settings loaded from environment variables."""
    
    # Application
    app_name: str = "AI Content Creator"
    app_env: str = "development"
    debug: bool = True
    secret_key: str = "dev-secret-key-change-in-production"
    
    # Database - Default to PostgreSQL (use environment variable)
    database_url: str = "postgresql://aiplatform:changeme@localhost:5432/ai_content_platform"
    
    # Redis
    redis_url: Optional[str] = None
    
    # RabbitMQ
    rabbitmq_url: Optional[str] = None
    
    # API
    api_host: str = "0.0.0.0"
    api_port: int = 8000
    
    # JWT
    jwt_secret: str = "your-jwt-secret-change-this"
    jwt_algorithm: str = "HS256"
    jwt_expiration_hours: int = 24
    
    # GPU
    cuda_visible_devices: str = "0"
    use_gpu: bool = True
    
    # Models
    models_dir: str = "./models"
    musicgen_model: str = "facebook/musicgen-small"
    xtts_model: str = "tts_models/multilingual/multi-dataset/xtts_v2"
    
    # Storage
    media_root: str = "./media"
    max_upload_size_mb: int = 100
    
    # Social Media APIs
    youtube_api_key: Optional[str] = None
    tiktok_client_key: Optional[str] = None
    tiktok_client_secret: Optional[str] = None
    twitter_api_key: Optional[str] = None
    twitter_api_secret: Optional[str] = None
    facebook_app_id: Optional[str] = None
    facebook_app_secret: Optional[str] = None
    
    # External APIs
    veo3_api_key: Optional[str] = None
    veo3_api_url: Optional[str] = None
    
    # Stripe
    stripe_secret_key: Optional[str] = None
    stripe_publishable_key: Optional[str] = None
    stripe_webhook_secret: Optional[str] = None
    stripe_price_id_pro: Optional[str] = None
    stripe_price_id_enterprise: Optional[str] = None
    
    # Email Service
    email_provider: str = "smtp"  # smtp, sendgrid, ses
    email_from: str = "noreply@example.com"
    email_from_name: str = "AI Content Creator"
    
    # SMTP settings
    smtp_host: Optional[str] = None
    smtp_port: int = 587
    smtp_username: Optional[str] = None
    smtp_password: Optional[str] = None
    smtp_use_tls: bool = True
    
    # SendGrid
    sendgrid_api_key: Optional[str] = None
    
    # AWS SES
    aws_access_key_id: Optional[str] = None
    aws_secret_access_key: Optional[str] = None
    aws_region: str = "us-east-1"

    # Monitoring
    prometheus_port: int = 9090
    
    # Service URLs
    auth_service_url: str = "http://localhost:8001"
    audio_service_url: str = "http://localhost:8002"
    video_service_url: str = "http://localhost:8003"
    sync_service_url: str = "http://localhost:8004"
    orchestration_service_url: str = "http://localhost:8005"
    publishing_service_url: str = "http://localhost:8006"
    
    # Features
    enable_video_generation: bool = True
    enable_social_publishing: bool = True
    enable_voice_cloning: bool = False
    
    class Config:
        env_file = ".env"
        case_sensitive = False
    
    def validate_production_settings(self):
        """Validate critical settings for production deployment."""
        if not self.debug:
            errors = []
            
            # Check JWT secret
            if self.jwt_secret == "your-jwt-secret-change-this":
                errors.append("JWT_SECRET must be changed from default in production")
            
            # Check app secret
            if self.secret_key == "dev-secret-key-change-in-production":
                errors.append("SECRET_KEY must be changed from default in production")
            
            # Check Stripe if monetization enabled
            if not self.stripe_secret_key:
                errors.append("STRIPE_SECRET_KEY is required in production")
            
            if errors:
                raise ValueError(f"Production configuration errors: {'; '.join(errors)}")


# Global settings instance
settings = Settings()


def get_settings() -> Settings:
    """Get application settings.
    
    Returns:
        Settings instance
    """
    return settings


def ensure_directories():
    """Ensure required directories exist."""
    directories = [
        settings.models_dir,
        settings.media_root,
        os.path.join(settings.media_root, "audio"),
        os.path.join(settings.media_root, "video"),
        os.path.join(settings.media_root, "final"),
        "data",
        "logs",
    ]
    
    for directory in directories:
        os.makedirs(directory, exist_ok=True)
