"""Keiro gateway provider.

Thin subclass of TakumiProvider with Keiro-specific credential and URL
resolution. Credentials are read from ``~/.keiro/credentials`` (written by
``keiro setup``), with env-var and ember-config fallbacks.

Resolution order for api_key:
    1. Explicit ``api_key`` kwarg
    2. ``KEIRO_API_KEY`` environment variable
    3. ``~/.keiro/credentials``
    4. ``providers.keiro.api_key`` in ``~/.ember/config.yaml`` (legacy)

Resolution order for base_url:
    1. Explicit ``base_url`` kwarg
    2. ``KEIRO_BASE_URL`` environment variable
    3. ``~/.keiro/credentials``
    4. ``providers.keiro.base_url`` in ``~/.ember/config.yaml`` (legacy)
    5. Hardcoded default gateway
"""

from __future__ import annotations

import logging
import os
from typing import Any, Generator, Optional  # noqa: F401 — Any/Generator needed for annotation resolution

from ember.models.schemas import ChatResponse  # noqa: F401 — ditto
from keiro.defaults import DEFAULT_GATEWAY_URL
from keiro.providers.takumi import TakumiProvider

logger = logging.getLogger(__name__)


class KeirProvider(TakumiProvider):
    """Keiro inference gateway provider."""

    requires_api_key = True
    supports_responses_api = True

    def _get_api_key_from_env(self) -> str:
        """Resolve API key: env > ~/.keiro/credentials > ember config."""
        env_key = os.environ.get("KEIRO_API_KEY")
        if env_key:
            return env_key

        from keiro.credentials import load_credentials

        creds = load_credentials()
        if creds.get("api_key"):
            return creds["api_key"]

        # Legacy fallback: ember config.
        try:
            from ember._internal.context.runtime import EmberContext

            ctx = EmberContext.current()
            config_key = ctx.get_config("providers.keiro.api_key")
            if isinstance(config_key, str) and config_key.strip():
                return config_key.strip()
        except Exception:
            logger.debug("EmberContext unavailable for Keiro API key", exc_info=True)

        raise ValueError(
            "Keiro API key not configured. Run 'keiro setup' or set KEIRO_API_KEY."
        )

    def _resolve_base_url(self, explicit_base_url: Optional[str]) -> str:
        """Resolve base URL: explicit > env > credentials > ember config > default."""
        if explicit_base_url:
            return explicit_base_url.rstrip("/")

        env_url = os.environ.get("KEIRO_BASE_URL")
        if env_url:
            return env_url.rstrip("/")

        from keiro.credentials import load_credentials

        creds = load_credentials()
        if creds.get("base_url"):
            return creds["base_url"].rstrip("/")

        # Legacy fallback: ember config.
        try:
            from ember._internal.context.runtime import EmberContext

            ctx = EmberContext.current()
            config_url = ctx.get_config("providers.keiro.base_url")
            if isinstance(config_url, str) and config_url.strip():
                return config_url.strip().rstrip("/")
        except Exception:
            logger.debug(
                "EmberContext unavailable for Keiro base URL", exc_info=True
            )

        return DEFAULT_GATEWAY_URL
