"""Server configuration: dual-source loading from YAML file and environment variables."""

from __future__ import annotations

import logging
import os
from pathlib import Path

import yaml
from pydantic import BaseModel

logger = logging.getLogger("vmcluster_mcp.config")

_ENV_MAP = {
    "VMCLUSTER_TOPOLOGY_DIR": "topology_dir",
    "VMCLUSTER_OVERLAY_DIR": "overlay_dir",
    "VMCLUSTER_ARTIFACT_REGISTRY": "artifact_registry",
    "VMCLUSTER_ARTIFACT_STORE_DIR": "artifact_store_dir",
    "VMCLUSTER_FAULT_REGISTRY": "fault_registry",
    "VMCLUSTER_SSH_KEY_PATH": "ssh_key_path",
    "VMCLUSTER_SSH_USER": "ssh_user",
    "VMCLUSTER_LIBVIRT_URI": "libvirt_uri",
    "VMCLUSTER_LOG_LEVEL": "log_level",
}


class Config(BaseModel):
    topology_dir: str = "/etc/vmcluster/topologies"
    overlay_dir: str = "/var/lib/vmcluster/overlays"
    artifact_registry: str = "/var/lib/vmcluster/artifacts/registry.json"
    artifact_store_dir: str = "/var/lib/vmcluster/artifacts/trees"
    fault_registry: str = "/var/lib/vmcluster/faults/registry.json"
    ssh_key_path: str = "/etc/vmcluster/ssh/vmcluster_id_ed25519"
    ssh_user: str = "root"
    libvirt_uri: str = "qemu:///system"
    log_level: str = "INFO"


def load_config() -> Config:
    """Load configuration from YAML file and/or environment variables.

    Priority: env vars > file values > defaults.
    File path: VMCLUSTER_CONFIG env var or /etc/vmcluster/config.yaml.
    """
    config_path = os.environ.get("VMCLUSTER_CONFIG", "/etc/vmcluster/config.yaml")
    values: dict = {}

    if Path(config_path).is_file():
        with open(config_path) as f:
            file_values = yaml.safe_load(f)
        if isinstance(file_values, dict):
            values.update(file_values)
        logger.info("Config loaded from %s", config_path)
    else:
        logger.info("Config file not found at %s, using defaults + env vars", config_path)

    for env_key, field_name in _ENV_MAP.items():
        env_val = os.environ.get(env_key)
        if env_val is not None:
            values[field_name] = env_val

    return Config(**values)
