"""Configuration management for OpenClaw Sandbox CLI."""

import os
from pathlib import Path

import yaml

from .const import CONFIG_DIR_NAME, CONFIG_SECTION, ENV_VAR_API_KEY

CONFIG_DIR = Path.home() / CONFIG_DIR_NAME
CONFIG_FILE = CONFIG_DIR / "config.yaml"

DEFAULT_CONFIG = {
    CONFIG_SECTION: {
        "api_key": "",
        "template_id": "",
    },
}


def ensure_config_dir():
    """Ensure the configuration directory exists."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)


def load_config() -> dict:
    """Load configuration from YAML file, merging with defaults."""
    ensure_config_dir()
    try:
        with open(CONFIG_FILE) as f:
            user_config = yaml.safe_load(f) or {}
        config = _deep_merge(DEFAULT_CONFIG, user_config)
    except FileNotFoundError:
        config = DEFAULT_CONFIG.copy()
    # Override with environment variables
    _apply_env_overrides(config)
    return config


def save_config(config: dict):
    """Save configuration to YAML file."""
    ensure_config_dir()
    with open(CONFIG_FILE, "w") as f:
        yaml.dump(config, f, default_flow_style=False, allow_unicode=True)



def _deep_merge(base: dict, override: dict) -> dict:
    """Deep merge two dictionaries."""
    result = base.copy()
    for key, value in override.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = _deep_merge(result[key], value)
        else:
            result[key] = value
    return result


def _apply_env_overrides(config: dict):
    """Apply environment variable overrides to config."""
    env_map = {
        ENV_VAR_API_KEY: (CONFIG_SECTION, "api_key"),
    }
    for env_var, path in env_map.items():
        value = os.environ.get(env_var)
        if value:
            section, key = path
            config[section][key] = value
