"""
Configuration management for KPI Analysis Application
Handles environment variables and settings for Nextcloud, OpenAI, LDAP, etc.
"""

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

class Settings(BaseSettings):
    """Application settings with environment variable support"""
    
    # Application Settings
    app_name: str = "KPI Analysis Dashboard"
    app_version: str = "1.0.0"
    debug: bool = False
    secret_key: str = "your-secret-key-here-change-in-production"
    
    # Server Settings
    host: str = "0.0.0.0"
    port: int = 8000
    
    # Nextcloud Configuration
    nextcloud_base_url: str = "https://nc.mapan.co.id"
    nextcloud_oauth_client_id: Optional[str] = None
    nextcloud_oauth_client_secret: Optional[str] = None
    nextcloud_redirect_uri: str = "http://localhost:8000/auth/nextcloud/callback"
    nextcloud_kpi_folder: str = "/KPI_Files"
    nextcloud_username: Optional[str] = None
    
    # OpenAI Configuration
    openai_api_key: Optional[str] = None
    openai_model: str = "gpt-4"
    openai_max_tokens: int = 2000
    openai_temperature: float = 0.7
    
    # LDAP/Active Directory Configuration
    ldap_server: Optional[str] = None
    ldap_port: int = 389
    ldap_use_ssl: bool = True
    ldap_base_dn: Optional[str] = None
    ldap_bind_dn: Optional[str] = None
    ldap_bind_password: Optional[str] = None
    ldap_user_search_filter: str = "(uid={username})"
    ldap_group_base_dn: Optional[str] = None
    ldap_kpi_group_dn: Optional[str] = None
    ldap_kpi_group_name: str = "KPI_Users"
    ldap_group_member_attribute: str = "member"
    ldap_user_member_attribute: str = "memberOf"
    
    # Fallback Authentication (for testing/development when LDAP not available)
    enable_fallback_auth: bool = False
    fallback_admin_username: str = "admin"
    fallback_admin_password: str = "super"
    fallback_admin_role: str = "admin"
    fallback_admin_email: str = "admin@kpi-system.local"
    
    # Database Settings
    database_url: str = "sqlite:///./data/kpi_analysis.db"
    
    # File Storage
    data_directory: str = "./data"
    upload_directory: str = "./uploads"
    reports_directory: str = "./reports"
    
    # Email Configuration (for notifications)
    smtp_server: Optional[str] = None
    smtp_port: int = 587
    smtp_username: Optional[str] = None
    smtp_password: Optional[str] = None
    email_from: Optional[str] = None
    
    # Security Settings
    session_timeout_minutes: int = 60
    max_file_size_mb: int = 50
    allowed_file_extensions: List[str] = [".xlsx", ".xls"]
    
    # CORS Settings
    cors_allow_origins: Optional[List[str]] = None  # If None, will use default domains
    
    @property
    def default_cors_origins(self) -> List[str]:
        """Default CORS origins based on server configuration"""
        # Start with common development ports
        origins = [
            "http://localhost:3000",
            "http://localhost:8000", 
            "http://127.0.0.1:8000",
            "http://localhost:8080"
        ]
        
        # Add production domain based on server host if not localhost
        if self.host not in ["0.0.0.0", "127.0.0.1", "localhost"]:
            scheme = "https" if self.port == 443 else "http"
            origins.append(f"{scheme}://{self.host}")
        
        # Add localhost with current port for development (avoid duplicates)
        localhost_origin = f"http://localhost:{self.port}"
        if localhost_origin not in origins:
            origins.append(localhost_origin)
            
        localnet_origin = f"http://127.0.0.1:{self.port}"
        if localnet_origin not in origins:
            origins.append(localnet_origin)
        
        return list(set(origins))  # Remove any duplicates
    
    @property
    def effective_cors_origins(self) -> List[str]:
        """Get effective CORS origins (custom or default)"""
        if self.cors_allow_origins:
            return self.cors_allow_origins
        return self.default_cors_origins
    
    # Logging
    log_level: str = "INFO"
    log_file: str = "./logs/kpi_analysis.log"
    
    class Config:
        # Use absolute path to .env file relative to this settings.py file
        import os
        from pathlib import Path
        _settings_dir = Path(__file__).parent.parent  # Go up to kpi_analysis directory
        env_file = str(_settings_dir / ".env")
        env_file_encoding = "utf-8"
        case_sensitive = False

# Global settings instance
settings = Settings()

# Debug: Log which .env file is being used
import logging
logger = logging.getLogger(__name__)
from pathlib import Path
env_file_path = Path(__file__).parent.parent / ".env"
if env_file_path.exists():
    logger.info(f"✅ .env file found at: {env_file_path}")
    logger.info(f"   Fallback auth enabled: {settings.enable_fallback_auth}")
else:
    logger.warning(f"⚠️  .env file not found at: {env_file_path}")

# Ensure directories exist
os.makedirs(settings.data_directory, exist_ok=True)
os.makedirs(settings.upload_directory, exist_ok=True)
os.makedirs(settings.reports_directory, exist_ok=True)

# Create logs directory
os.makedirs(os.path.dirname(settings.log_file), exist_ok=True)