import os
import yaml
from dotenv import load_dotenv

class BaseAIConfig:
    def __init__(self):
        load_dotenv()
        self.config = self._load_config()
        self.base_url = self._get_config_value('diona.ai.modelset.base-url')
        self.api_key = self._get_api_key()
        self.model = self._get_config_value('diona.ai.modelset.model')
        self.proxy = self._get_config_value('diona.ai.clientset.proxy', False)
        self.use_proxy = self._get_config_value('diona.ai.clientset.use-proxy', False)
    
    def _load_config(self):
        config_path = os.path.join(os.getcwd(), 'config.yml')
        if os.path.exists(config_path):
            with open(config_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        return {}
    
    def _get_config_value(self, key, default=None):
        keys = key.split('.')
        value = self.config
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        return value
    
    def _get_api_key(self):
        # Priority: 1. Environment variable 2. .env file 3. config.yml
        api_key = os.environ.get('OPENAI_API_KEY')
        if api_key:
            return api_key
        api_key = self._get_config_value('diona.ai.modelset.api-key')
        return api_key
    
    def get_base_url(self):
        return self.base_url
    
    def get_api_key(self):
        return self.api_key
    
    def get_model(self):
        return self.model
    
    def get_proxy(self):
        return self.proxy
    
    def is_use_proxy(self):
        return self.use_proxy