"""
配置管理模块
"""
import os
import yaml
import logging
from typing import Optional, Dict, Any

logger = logging.getLogger(__name__)

# 默认配置
DEFAULT_CONFIG = {
    "vlm": {
        "enabled": False,
        "provider": "openai",
        "model": "gpt-4o",
        "api_key": "",
        "base_url": "",
        "prompt": ""
    },
    "server": {
        "port": 50051,
        "max_workers": 10,
        "log_level": "INFO"
    }
}


def load_config(config_path: Optional[str] = None) -> Dict[str, Any]:
    """加载配置文件"""
    if config_path is None:
        # 默认查找 config.yaml
        base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        config_path = os.path.join(base_dir, "config.yaml")

    # 环境变量覆盖
    vlm_api_key = os.environ.get("VLM_API_KEY", "")
    if vlm_api_key:
        DEFAULT_CONFIG["vlm"]["api_key"] = vlm_api_key
        DEFAULT_CONFIG["vlm"]["enabled"] = True
        logger.info("VLM enabled via environment variable")

    vlm_provider = os.environ.get("VLM_PROVIDER", "")
    if vlm_provider:
        DEFAULT_CONFIG["vlm"]["provider"] = vlm_provider

    vlm_model = os.environ.get("VLM_MODEL", "")
    if vlm_model:
        DEFAULT_CONFIG["vlm"]["model"] = vlm_model

    # 尝试加载配置文件
    if os.path.exists(config_path):
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                file_config = yaml.safe_load(f)
                if file_config:
                    # 合并配置
                    for key in file_config:
                        if key in DEFAULT_CONFIG:
                            DEFAULT_CONFIG[key].update(file_config[key])
                    logger.info(f"Loaded config from {config_path}")
        except Exception as e:
            logger.warning(f"Failed to load config: {e}")

    # 检查 VLM 是否有效
    if DEFAULT_CONFIG["vlm"]["enabled"] and not DEFAULT_CONFIG["vlm"]["api_key"]:
        logger.warning("VLM enabled but API key is empty, disabling VLM")
        DEFAULT_CONFIG["vlm"]["enabled"] = False

    return DEFAULT_CONFIG


def get_vlm_config() -> Optional[Dict[str, Any]]:
    """获取 VLM 配置"""
    config = load_config()
    if config.get("vlm", {}).get("enabled") and config["vlm"].get("api_key"):
        return config["vlm"]
    return None


def get_server_config() -> Dict[str, Any]:
    """获取服务器配置"""
    config = load_config()
    return config.get("server", DEFAULT_CONFIG["server"])
