"""Client-specific configuration with priority over defaults"""

import os
from typing import Optional

import yaml


class ClientConfig:
    """Manages client-specific configuration overrides"""

    def __init__(self, config_dir: str = "."):
        self.config_dir = os.path.abspath(config_dir)
        self._clients: Optional[dict] = None

    @property
    def clients(self) -> dict:
        if self._clients is None:
            self._clients = self._load_clients()
        return self._clients

    def _load_clients(self) -> dict:
        clients_path = os.path.join(self.config_dir, "clients.yaml")
        if os.path.exists(clients_path):
            with open(clients_path, encoding="utf-8") as f:
                return yaml.safe_load(f) or {}
        return {}

    def reload(self):
        """Force reload clients.yaml"""
        self._clients = None

    def identify_client(self, api_key: str) -> Optional[str]:
        """Identify client name from API key"""
        for name, info in self.clients.items():
            if info.get("api_key") == api_key:
                return name
        return None

    def get_client_config(self, client_name: str) -> dict:
        """Get client-specific configuration"""
        return self.clients.get(client_name, {})

    def get_skills_dir(self, client_name: Optional[str] = None) -> Optional[str]:
        """Get skills directory for a client (client override > default)"""
        if client_name:
            client_info = self.get_client_config(client_name)
            if "skills_dir" in client_info:
                return client_info["skills_dir"]
        # Fall back to default from agentkit.yaml
        default_config = self._load_default_config()
        return default_config.get("skills", {}).get("paths", ["./skills"])[0] if default_config else None

    def _load_default_config(self) -> dict:
        config_path = os.path.join(self.config_dir, "agentkit.yaml")
        if os.path.exists(config_path):
            with open(config_path, encoding="utf-8") as f:
                return yaml.safe_load(f) or {}
        return {}

    def validate_api_key(self, api_key: str) -> bool:
        """Validate an API key against registered clients"""
        return self.identify_client(api_key) is not None
