"""Credential storage — thin wrappers over AuthStore.

All functions delegate to mcp_eregistrations_common.auth_store using
profile names as keys. Instance-id slugs are mapped to profile names
via _slug_to_name() for backwards compatibility with callers that
still pass config.instance_id.
"""

from __future__ import annotations

import logging

logger = logging.getLogger(__name__)

# Kept for migration / backwards compat (used by auth_store._migrate)
KEYRING_SERVICE_PREFIX = "mcp-eregistrations-bpa"

# Lazy-built slug -> profile name map (None = not yet built)
_slug_map: dict[str, str] | None = None


def _build_slug_map() -> dict[str, str]:
    """Build instance_id slug -> profile name mapping.

    Same logic as auth_store._build_slug_to_name_map().
    """
    mapping: dict[str, str] = {}
    try:
        from mcp_eregistrations_bpa.config import (
            _generate_instance_slug,
            load_profiles,
        )
        from mcp_eregistrations_common.config import load_builtin_instances

        for name, profile in load_profiles().items():
            url = profile.get("bpa_url", profile.get("bpa_instance_url", ""))
            if url:
                mapping[_generate_instance_slug(url)] = name
        for inst in load_builtin_instances():
            mapping[_generate_instance_slug(inst["bpa_url"])] = inst["name"]
    except Exception:
        pass
    return mapping


def _slug_to_name(instance_id: str) -> str:
    """Map an instance_id slug to its profile name.

    Returns the profile name if found, otherwise instance_id as-is.
    """
    global _slug_map  # noqa: PLW0603
    if _slug_map is None:
        _slug_map = _build_slug_map()
    return _slug_map.get(instance_id, instance_id)


def _remove_instance_fields(name: str, fields: list[str]) -> None:
    """Remove specific fields from an instance entry in AuthStore."""
    from mcp_eregistrations_common.auth_store import _load, _save

    data = _load()
    inst = data.get("instances", {}).get(name)
    if inst is None:
        return
    for field in fields:
        inst.pop(field, None)
    # Clean up empty instance entries
    if not inst:
        data.get("instances", {}).pop(name, None)
    _save(data)


# ---------------------------------------------------------------------------
# Credentials
# ---------------------------------------------------------------------------


def store_credentials(instance_id: str, username: str, password: str) -> bool:
    """Store credentials via AuthStore.

    Args:
        instance_id: BPA instance slug.
        username: BPA username (email).
        password: BPA password.

    Returns:
        True if stored successfully.
    """
    try:
        from mcp_eregistrations_common.auth_store import (
            store_credentials as _store,
        )

        name = _slug_to_name(instance_id)
        _store(name, username, password)
        return True
    except Exception as e:
        logger.warning("Cannot store credentials: %s", e)
        return False


def get_credentials(instance_id: str) -> tuple[str, str] | None:
    """Retrieve credentials from AuthStore.

    Args:
        instance_id: BPA instance slug.

    Returns:
        (username, password) tuple, or None if not found.
    """
    from mcp_eregistrations_common.auth_store import (
        get_credentials as _get,
    )

    name = _slug_to_name(instance_id)
    return _get(name)


def delete_credentials(instance_id: str) -> None:
    """Remove stored credentials. Silently ignores missing entries."""
    try:
        name = _slug_to_name(instance_id)
        _remove_instance_fields(name, ["username", "password"])
    except Exception:
        pass


# ---------------------------------------------------------------------------
# CAS client secret storage
# ---------------------------------------------------------------------------


def store_cas_secret(instance_id: str, secret: str) -> bool:
    """Store CAS client secret via AuthStore."""
    try:
        from mcp_eregistrations_common.auth_store import (
            store_cas_secret as _store_cas,
        )

        name = _slug_to_name(instance_id)
        _store_cas(name, secret)
        return True
    except Exception as e:
        logger.warning("Cannot store CAS secret: %s", e)
        return False


def get_cas_secret(instance_id: str) -> str | None:
    """Retrieve CAS client secret from AuthStore."""
    from mcp_eregistrations_common.auth_store import (
        get_cas_secret as _get_cas,
    )

    name = _slug_to_name(instance_id)
    return _get_cas(name)


def delete_cas_secret(instance_id: str) -> None:
    """Remove stored CAS client secret."""
    try:
        name = _slug_to_name(instance_id)
        _remove_instance_fields(name, ["cas_client_secret"])
    except Exception:
        pass


# ---------------------------------------------------------------------------
# Refresh context storage (cross-session token refresh)
# ---------------------------------------------------------------------------


def store_refresh_context(instance_id: str, context: dict[str, str]) -> bool:
    """Store refresh context via AuthStore for cross-session auth."""
    try:
        from mcp_eregistrations_common.auth_store import (
            store_refresh_context as _store_ctx,
        )

        name = _slug_to_name(instance_id)
        _store_ctx(
            name,
            refresh_token=context.get("refresh_token", ""),
            token_endpoint=context.get("token_endpoint", ""),
            client_id=context.get("client_id", ""),
            cas_client_secret=context.get("cas_client_secret"),
            redirect_uri=context.get("redirect_uri"),
        )
        return True
    except Exception as e:
        logger.warning("Cannot store refresh context: %s", e)
        return False


def get_refresh_context(instance_id: str) -> dict[str, str] | None:
    """Retrieve refresh context from AuthStore."""
    from mcp_eregistrations_common.auth_store import (
        get_refresh_context as _get_ctx,
    )

    name = _slug_to_name(instance_id)
    return _get_ctx(name)


def delete_refresh_context(instance_id: str) -> None:
    """Remove stored refresh context."""
    try:
        name = _slug_to_name(instance_id)
        _remove_instance_fields(name, ["refresh_token", "token_endpoint", "client_id"])
    except Exception:
        pass
