"""

Configuration Management for Swarm Portal



Uses shared.config.ConfigManager for unified configuration loading.



Load order:

1. Defaults (defined below)

2. .swarm_portal config file

3. .env file

4. Environment variables

5. CLI arguments (when applicable)

"""



import os

import sys

from pathlib import Path



# Import from installed shared library (installed via pip install -e)

from shared.config import ConfigManager



# Default configuration

DEFAULTS = {

    # Server settings

    'PORT': 5413,

    'HOST': '0.0.0.0',

    'BASE_PATH': '/io/studio',

    'DEBUG': False,



    # Authentication

    'PASSWORD': 'friendship',



    # LLM settings

    'PROVIDER': 'xai',

    'MODEL': 'grok-3',

    'TEMPERATURE': 0.7,

    'MAX_TOKENS': 16000,



    # Caching

    'CACHE_TTL': 3600,  # 1 hour

    'USE_REDIS': True,

    'REDIS_HOST': 'localhost',

    'REDIS_PORT': 6379,



    # Database

    'DB_TYPE': 'sqlite',  # sqlite or postgres

    'DB_PATH': 'swarm_portal.db',



    # Multi-agent search settings

    'DEFAULT_NUM_AGENTS': 5,

    'MAX_AGENTS': 9,

    'MIN_AGENTS': 1,

    'MAIN_MODEL': 'grok-3',

    'MINI_MODEL': 'grok-3-mini',



    # Rate limiting

    'RATE_LIMIT_PER_MINUTE': 60,

}





class SwarmPortalConfig:

    """

    Configuration manager for Swarm Portal.



    Wraps shared.config.ConfigManager with Portal-specific defaults.

    """



    def __init__(self, base_dir=None):

        """

        Initialize configuration manager.



        Args:

            base_dir: Base directory for config files (defaults to this file's directory)

        """

        if base_dir is None:

            base_dir = Path(__file__).parent



        self.config_manager = ConfigManager(

            app_name='swarm_portal',

            base_dir=base_dir,

            defaults=DEFAULTS,

            auto_load=True

        )



    def get(self, key, default=None):

        """Get configuration value"""

        return self.config_manager.get(key, default)



    def set(self, key, value):

        """Set configuration value"""

        self.config_manager.set(key, value)



    def get_api_key(self, provider=None):

        """

        Get API key for a provider.



        Args:

            provider: Provider name (if None, uses configured PROVIDER)



        Returns:

            API key string



        Raises:

            ValueError: If API key not found

        """

        api_key = self.config_manager.get_api_key(provider)

        if not api_key:

            provider_name = provider or self.get('PROVIDER', 'unknown')

            raise ValueError(

                f"API key not found for provider '{provider_name}'. "

                f"Set {provider_name.upper()}_API_KEY in .env or environment."

            )

        return api_key



    def has_api_key(self, provider):

        """Check if API key exists for provider"""

        return self.config_manager.has_api_key(provider)



    def list_available_providers(self):

        """List all providers with configured API keys"""

        return self.config_manager.list_available_providers()



    def as_dict(self, mask_secrets=True):

        """Get configuration as dictionary"""

        return self.config_manager.as_dict(mask_secrets=mask_secrets)



    def save(self, include_secrets=False):

        """Save configuration to file"""

        self.config_manager.save(include_secrets=include_secrets)



    def reload(self):

        """Reload configuration from all sources"""

        self.config_manager.reload()



    @property

    def port(self):

        """Server port"""

        return self.get('PORT')



    @property

    def host(self):

        """Server host"""

        return self.get('HOST')



    @property

    def base_path(self):

        """Base URL path for reverse proxy"""

        return self.get('BASE_PATH')



    @property

    def password(self):

        """Authentication password"""

        return self.get('PASSWORD')



    @property

    def debug(self):

        """Debug mode"""

        return self.get('DEBUG')



    @property

    def cache_ttl(self):

        """Cache TTL in seconds"""

        return self.get('CACHE_TTL')



    @property

    def use_redis(self):

        """Whether to use Redis for caching"""

        return self.get('USE_REDIS')



    @property

    def db_path(self):

        """Database file path"""

        return self.get('DB_PATH')





# Global config instance

_config = None





def get_config(reload=False):

    """

    Get global configuration instance.



    Args:

        reload: Whether to force reload config



    Returns:

        SwarmPortalConfig instance

    """

    global _config



    if _config is None or reload:

        _config = SwarmPortalConfig()



    return _config





# Convenience exports

__all__ = [

    'SwarmPortalConfig',

    'get_config',

    'DEFAULTS',

]



