"""
Configuration Storage

INI-based configuration storage with migration support.
"""

import configparser
import os
from pathlib import Path

from honeydb_ai.domain.exceptions import ConfigurationError, StorageError
from honeydb_ai.domain.interfaces import ConfigStore as ConfigStoreInterface
from honeydb_ai.domain.models import Config
from honeydb_ai.utils.logging import get_logger


class INIConfigStore(ConfigStoreInterface):
    """
    INI-based configuration storage.

    Format:
    ```ini
    [honeydb]
    api_id = your-honeydb-api-id
    api_key = your-honeydb-api-key
    mcp_server_url = https://honeydb.ai/sse/

    [llm]
    default_provider = openai
    openai_api_key = sk-...
    anthropic_api_key = sk-ant-...
    gemini_api_key = ...
    default_model = gpt-5.4
    temperature = 0.7
    max_tokens =

    [session]
    auto_save = true
    sessions_dir = ~/.honeydb_ai/sessions

    [ui]
    theme = auto
    markdown_enabled = true
    syntax_highlighting = true
    verbose_tool_calls = false

    [logging]
    log_level = INFO
    log_file = ~/.honeydb_ai/honeydb_ai.log
    log_max_size_mb = 5
    log_backup_count = 3
    ```
    """

    def __init__(self, config_path: str | Path):
        """
        Initialize config store.

        Args:
            config_path: Path to configuration file
        """
        self.config_path = Path(config_path).expanduser().resolve()
        self.logger = get_logger()

        # Ensure config directory exists
        self.config_path.parent.mkdir(parents=True, exist_ok=True)

    def load(self) -> Config:
        """
        Load configuration from storage.

        Returns:
            Config object with defaults for missing values

        Raises:
            ConfigurationError: If configuration is invalid
        """
        if not self.config_path.exists():
            self.logger.info("Config file not found, using defaults")
            return Config()

        try:
            parser = configparser.ConfigParser()
            parser.read(self.config_path)

            # Build config dict from INI
            config_dict = {}

            # HoneyDB MCP section
            if parser.has_section('honeydb'):
                honeydb = parser['honeydb']
                config_dict['honeydb_api_id'] = honeydb.get('api_id', None)
                config_dict['honeydb_api_key'] = honeydb.get('api_key', None)
                config_dict['mcp_server_url'] = honeydb.get('mcp_server_url', 'https://honeydb.ai/sse/')

            # LLM section
            if parser.has_section('llm'):
                llm = parser['llm']
                config_dict['default_provider'] = llm.get('default_provider', 'openai')
                config_dict['openai_api_key'] = llm.get('openai_api_key', None)
                config_dict['anthropic_api_key'] = llm.get('anthropic_api_key', None)
                config_dict['gemini_api_key'] = llm.get('gemini_api_key', None)
                config_dict['default_model'] = llm.get('default_model', 'gpt-5.4')
                config_dict['temperature'] = llm.getfloat('temperature', 0.7)

                max_tokens_str = llm.get('max_tokens', '')
                config_dict['max_tokens'] = int(max_tokens_str) if max_tokens_str else None

            # Session section
            if parser.has_section('session'):
                session = parser['session']
                config_dict['auto_save'] = session.getboolean('auto_save', True)
                config_dict['sessions_dir'] = session.get('sessions_dir', '~/.honeydb_ai/sessions')

            # UI section
            if parser.has_section('ui'):
                ui = parser['ui']
                config_dict['theme'] = ui.get('theme', 'auto')
                config_dict['markdown_enabled'] = ui.getboolean('markdown_enabled', True)
                config_dict['syntax_highlighting'] = ui.getboolean('syntax_highlighting', True)
                config_dict['verbose_tool_calls'] = ui.getboolean('verbose_tool_calls', False)

            # Logging section (v2.0)
            if parser.has_section('logging'):
                logging_section = parser['logging']
                config_dict['log_level'] = logging_section.get('log_level', 'INFO')
                config_dict['log_file'] = logging_section.get('log_file', '~/.honeydb_ai/honeydb_ai.log')
                config_dict['log_max_size_mb'] = logging_section.getint('log_max_size_mb', 5)
                config_dict['log_backup_count'] = logging_section.getint('log_backup_count', 3)

            config = Config(**config_dict)
            self.logger.info("Configuration loaded successfully")
            return config

        except Exception as e:
            self.logger.error(f"Failed to load configuration: {e}")
            raise ConfigurationError(f"Failed to load config from {self.config_path}: {e}")

    def save(self, config: Config) -> None:
        """
        Save configuration to storage.

        Raises:
            StorageError: If save fails
        """
        try:
            parser = configparser.ConfigParser()

            # HoneyDB MCP section
            parser['honeydb'] = {
                'api_id': config.honeydb_api_id or '',
                'api_key': config.honeydb_api_key or '',
                'mcp_server_url': config.mcp_server_url,
            }

            # LLM section
            parser['llm'] = {
                'default_provider': config.default_provider,
                'openai_api_key': config.openai_api_key or '',
                'anthropic_api_key': config.anthropic_api_key or '',
                'gemini_api_key': config.gemini_api_key or '',
                'default_model': config.default_model,
                'temperature': str(config.temperature),
                'max_tokens': str(config.max_tokens) if config.max_tokens else '',
            }

            # Session section
            parser['session'] = {
                'auto_save': str(config.auto_save).lower(),
                'sessions_dir': config.sessions_dir,
            }

            # UI section
            parser['ui'] = {
                'theme': config.theme,
                'markdown_enabled': str(config.markdown_enabled).lower(),
                'syntax_highlighting': str(config.syntax_highlighting).lower(),
                'verbose_tool_calls': str(config.verbose_tool_calls).lower(),
            }

            # Logging section (v2.0)
            parser['logging'] = {
                'log_level': config.log_level,
                'log_file': config.log_file,
                'log_max_size_mb': str(config.log_max_size_mb),
                'log_backup_count': str(config.log_backup_count),
            }

            # Write to file
            with open(self.config_path, 'w') as f:
                parser.write(f)

            # Set restrictive permissions
            os.chmod(self.config_path, 0o600)

            self.logger.info("Configuration saved successfully")

        except Exception as e:
            self.logger.error(f"Failed to save configuration: {e}")
            raise StorageError(f"Failed to save config to {self.config_path}: {e}")

    def exists(self) -> bool:
        """Check if configuration file exists."""
        return self.config_path.exists()

    def get_config_path(self) -> Path:
        """Get the configuration file path."""
        return self.config_path

    def migrate_from_v1(self) -> None:
        """
        Migrate configuration from v1.0 format.

        v2.0: Adds logging section and new fields while preserving existing settings.
        """
        if not self.config_path.exists():
            return

        try:
            # Load current config
            config = self.load()

            # Save with new format (will add logging section with defaults)
            self.save(config)

            self.logger.info("Configuration migrated to v2.0 format")

        except Exception as e:
            self.logger.warning(f"Failed to migrate configuration: {e}")
