"""Configuration management for the AI CLI client"""

import os
import yaml
from typing import Dict, Any, Optional
from dotenv import load_dotenv


class AppConfig:
    """Application configuration data model"""
    
    def __init__(self):
        """Initialize application configuration"""
        self.ai_config: Dict[str, Any] = {
            "base-url": "https://api.deepseek.com/v1",
            "api-key": "",
            "model": "deepseek-chat"
        }
        self.ui_config: Dict[str, Any] = {
            "markdown-enabled": False,
            "stream-output": True
        }
        self.tools_config: Dict[str, Any] = {
            "enabled": True,
            "filesystem": {
                "enabled": True,
                "root": "."
            },
            "shell": {
                "enabled": True,
                "safe-mode": True
            },
            "git": {
                "enabled": True
            },
            "websearch": {
                "enabled": False,
                "api-key": ""
            }
        }
        self.agent_config: Dict[str, Any] = {
            "enabled": True,
            "temperature": 0.7,
            "max-tool-calls": 5,
            "system-prompt": "You are a helpful AI assistant with access to various tools. Use them when needed to provide accurate information."
        }


class ConfigManager:
    """Configuration manager (singleton)"""
    
    _instance = None
    
    def __new__(cls):
        """Create singleton instance"""
        if cls._instance is None:
            cls._instance = super(ConfigManager, cls).__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        """Initialize configuration manager"""
        if not self._initialized:
            self.config = AppConfig()
            self.load_config()
            self._initialized = True
    
    def load_config(self):
        """Load configuration from various sources"""
        # Load from config.yml
        self._load_from_yml()
        
        # Load from .env file
        load_dotenv()
        
        # Load from environment variables
        self._load_from_env()
    
    def _load_from_yml(self):
        """Load configuration from config.yml"""
        config_path = "config.yml"
        if os.path.exists(config_path):
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    data = yaml.safe_load(f)
                    if data and 'diona' in data and 'ai' in data['diona']:
                        ai_data = data['diona']['ai']
                        # Load modelset
                        if 'modelset' in ai_data:
                            self.config.ai_config.update(ai_data['modelset'])
                        # Load simplecli config
                        if 'simplecli' in ai_data:
                            simplecli_data = ai_data['simplecli']
                            if 'ui' in simplecli_data:
                                self.config.ui_config.update(simplecli_data['ui'])
                            if 'tools' in simplecli_data:
                                self.config.tools_config.update(simplecli_data['tools'])
                            if 'agent' in simplecli_data:
                                self.config.agent_config.update(simplecli_data['agent'])
            except Exception as e:
                print(f"Error loading config.yml: {e}")
    
    def _load_from_env(self):
        """Load configuration from environment variables"""
        # Load API key from environment
        if os.environ.get('OPENAI_API_KEY'):
            self.config.ai_config['api-key'] = os.environ['OPENAI_API_KEY']
        
        # Load model from environment
        if os.environ.get('OPENAI_MODEL'):
            self.config.ai_config['model'] = os.environ['OPENAI_MODEL']
        
        # Load base URL from environment
        if os.environ.get('OPENAI_BASE_URL'):
            self.config.ai_config['base-url'] = os.environ['OPENAI_BASE_URL']
    
    def get_ai_config(self) -> Dict[str, Any]:
        """Get AI model configuration"""
        return self.config.ai_config
    
    def get_ui_config(self) -> Dict[str, Any]:
        """Get UI configuration"""
        return self.config.ui_config
    
    def get_tools_config(self) -> Dict[str, Any]:
        """Get tools system configuration"""
        return self.config.tools_config
    
    def get_agent_config(self) -> Dict[str, Any]:
        """Get AI agent configuration"""
        return self.config.agent_config
    
    def validate(self) -> bool:
        """Validate configuration"""
        # Check if API key is set
        if not self.config.ai_config.get('api-key'):
            print("Error: OPENAI_API_KEY is not set")
            return False
        return True
    
    def update_model(self, model: str):
        """Update model at runtime"""
        self.config.ai_config['model'] = model
