"""Configuration settings for Restaurant Website Generator."""

import os
from typing import List, Optional
from pydantic_settings import BaseSettings
from fastapi import Request

class Settings(BaseSettings):
    """Application settings for Restaurant Website Generator."""
    
    # Server Configuration
    app_port: int = int(os.getenv("APP_PORT", "8000"))
    debug: bool = os.getenv("DEBUG", "True").lower() == "true"
    
    # OpenRouter API Configuration
    openrouter_api_key: str = os.getenv("OPENROUTER_API_KEY", "")
    openrouter_title: str = os.getenv("OPENROUTER_TITLE", "Restaurant-Website-Generator")
    
    def get_current_domain(self, request: Optional[Request] = None) -> str:
        """Auto-detect current domain, protocol, and port from request context."""
        if request:
            # Get protocol from request
            protocol = request.url.scheme
            
            # Get host from request headers (handles proxies, load balancers, etc.)
            host = request.headers.get("host", request.url.hostname or "localhost")
            
            # Remove port from host if it's already included
            if ":" in host:
                host = host.split(":")[0]
            
            # Get port from request or use default
            port = request.url.port or (443 if protocol == "https" else 80)
            
            # Only include port in URL if it's not the default port
            if (protocol == "http" and port == 80) or (protocol == "https" and port == 443):
                return f"{protocol}://{host}"
            else:
                return f"{protocol}://{host}:{port}"
        else:
            # Fallback for when no request is available
            return f"http://localhost:{self.app_port}"
    
    @property
    def openrouter_referrer(self) -> str:
        """Auto-detect OpenRouter referrer URL."""
        return self.get_current_domain()
    
    # AI Model Configuration
    agent_model: str = os.getenv("AGENT_MODEL", "gpt-4o-mini")
    temperature: float = float(os.getenv("TEMPERATURE", "0.7"))
    max_tokens: int = int(os.getenv("MAX_TOKENS", "8000"))
    
    # Rate Limiting (simplified - IP-based only)
    max_requests_per_ip: int = int(os.getenv("MAX_REQUESTS_PER_IP", "4"))
    max_requests_window: int = int(os.getenv("MAX_REQUESTS_WINDOW", "3600"))
    
    # Security
    secret_key: str = os.getenv("SECRET_KEY", "your-secret-key-here-change-in-production")
    
    def get_allowed_origins(self, request: Optional[Request] = None) -> List[str]:
        """Auto-detect allowed origins for CORS from request context."""
        current_domain = self.get_current_domain(request)
        
        # Get the base domain without port for variations
        if "://" in current_domain:
            protocol, domain_with_port = current_domain.split("://", 1)
            domain = domain_with_port.split(":")[0] if ":" in domain_with_port else domain_with_port
        else:
            protocol = "http"
            domain = "localhost"
        
        # Create multiple origin variations
        origins = [
            current_domain,  # The exact current domain
            f"{protocol}://{domain}",  # Without port
            f"{protocol}://localhost",  # Localhost variant
            f"{protocol}://127.0.0.1",  # 127.0.0.1 variant
        ]
        
        # Add HTTPS variant if we're using HTTP
        if protocol == "http":
            origins.extend([
                f"https://{domain}",
                f"https://localhost",
                f"https://127.0.0.1",
            ])
        
        # Add HTTP variant if we're using HTTPS
        if protocol == "https":
            origins.extend([
                f"http://{domain}",
                f"http://localhost",
                f"http://127.0.0.1",
            ])
        
        # Remove duplicates and return
        return list(set(origins))
    
    @property
    def allowed_origins(self) -> List[str]:
        """Auto-detect allowed origins for CORS."""
        return self.get_allowed_origins()
    
    # Restaurant Website Generator Specific Settings
    templates_dir: str = os.getenv("TEMPLATES_DIR", "templates")
    generated_dir: str = os.getenv("GENERATED_DIR", "templates/generated")
    uploads_dir: str = os.getenv("UPLOADS_DIR", "uploads")
    temp_logos_dir: str = os.getenv("TEMP_LOGOS_DIR", "temp_logos")
    
    # Email Configuration (for sending generated websites)
    smtp_server: str = os.getenv("SMTP_SERVER", "smtp.gmail.com")
    smtp_port: int = int(os.getenv("SMTP_PORT", "587"))
    smtp_username: str = os.getenv("SMTP_USERNAME", "")
    smtp_password: str = os.getenv("SMTP_PASSWORD", "")
    
    # Database Configuration (MySQL for rate limiting)
    database_url: str = os.getenv("DATABASE_URL", "mysql://root:@localhost:3306/restaurant_website_generator")
    db_host: str = os.getenv("DB_HOST", "localhost")
    db_port: int = int(os.getenv("DB_PORT", "3306"))
    db_name: str = os.getenv("DB_NAME", "restaurant_website_generator")
    db_user: str = os.getenv("DB_USER", "root")
    db_password: str = os.getenv("DB_PASSWORD", "")
    
    # LangSmith Configuration
    langsmith_api_key: str = os.getenv("LANGSMITH_API_KEY", "")
    langsmith_project: str = os.getenv("LANGSMITH_PROJECT", "restaurant-website-generator")
    langsmith_tracing: bool = os.getenv("LANGSMITH_TRACING", "true").lower() == "true"
    
    # OpenRouter Provider Configuration
    provider_order: str = os.getenv("PROVIDER_ORDER", "together,fireworks,perplexity")
    provider_allow_fallbacks: bool = os.getenv("PROVIDER_ALLOW_FALLBACKS", "true").lower() == "true"
    provider_ignore: str = os.getenv("PROVIDER_IGNORE", "azure")
    provider_data_collection: str = os.getenv("PROVIDER_DATA_COLLECTION", "deny")
    
    class Config:
        env_file = ".env"
        extra = "ignore"  # Ignore extra fields instead of raising error

# Global settings instance
settings = Settings()