import logging

from .auth import get_auth_context
from .config import get_account_url

logger = logging.getLogger("iis_access")

# In-memory cache for managed keys (process lifetime)
_key_cache: dict[str, str] = {}


async def get_managed_key(provider: str) -> str | None:
    """
    Retrieve user's managed API key for a provider from iis-account.
    Returns None if not authenticated, no key exists, or unreachable.
    """
    if provider in _key_cache:
        return _key_cache[provider]

    context = await get_auth_context()
    if context is None:
        return None

    try:
        import aiohttp

        account_url = get_account_url()
        timeout = aiohttp.ClientTimeout(total=5)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            resp = await session.get(
                f"{account_url}/keys/managed/{provider}",
                headers={"Authorization": f"Bearer {context.access_token}"},
            )
            if resp.status == 200:
                data = await resp.json()
                key = data.get("key")
                if key:
                    _key_cache[provider] = key
                    return key
            elif resp.status == 404:
                logger.debug("No managed key for provider '%s'", provider)
            else:
                logger.debug(
                    "Managed key retrieval failed (status %d)", resp.status
                )
    except Exception as e:
        logger.debug("Managed key retrieval failed (non-fatal): %s", e)

    return None


def _reset_key_cache() -> None:
    """Reset managed key cache (for testing)."""
    _key_cache.clear()
