"""Client factory for wiring shared backend implementations."""

from __future__ import annotations

try:
    from shared import BackendClient, BackendConfig, HttpBackendClient, MockBackendClient
    from shared import ConfigError as SharedConfigError
except ImportError:
    from cli._vendor.shared import (
        BackendClient,
        BackendConfig,
        HttpBackendClient,
        MockBackendClient,
    )
    from cli._vendor.shared import ConfigError as SharedConfigError

from .config import CLIConfig
from .exceptions import ConfigurationError
from .keychain import get_api_key_with_env_override


class ClientFactory:
    """Selects the appropriate backend client."""

    def build(self, config: CLIConfig) -> BackendClient:
        """Create a backend client based on configuration."""
        if config.use_mock_client:
            return MockBackendClient()

        if not config.api_base_url:
            raise ConfigurationError(
                "API base URL is not configured. Run 'ctxme config --api <url>'.",
            )

        api_key, _ = get_api_key_with_env_override()
        if not api_key:
            raise ConfigurationError(
                "API key is not set. Run 'ctxme auth login' or "
                "'ctxme auth set-key <key>' before using live mode.",
            )

        try:
            backend_config = BackendConfig(api_base_url=config.api_base_url, api_key=api_key)
        except SharedConfigError as exc:
            raise ConfigurationError(str(exc)) from exc

        return HttpBackendClient(backend_config)
