"""MCP authentication helpers."""

from typing import Any

from pydanticai_multiagent.services.tenant import Tenant, TenantService


class MCPAuthError(Exception):
    """Authentication error for MCP tools."""

    def __init__(self, message: str = "Invalid API key") -> None:
        self.message = message
        super().__init__(message)


async def validate_api_key(api_key: str, db: Any) -> Tenant:
    """Validate an API key and return the tenant.

    Args:
        api_key: The tenant API key (sk-tenant-xxx format).
        db: Database connection pool.

    Returns:
        The authenticated Tenant.

    Raises:
        MCPAuthError: If the API key is invalid or tenant is inactive.
    """
    if not api_key:
        raise MCPAuthError("API key is required")

    if not api_key.startswith("sk-tenant-"):
        raise MCPAuthError("Invalid API key format. Expected sk-tenant-xxx")

    if not db:
        raise MCPAuthError("Database not configured")

    tenant_service = TenantService(db)
    tenant = await tenant_service.get_tenant_by_api_key(api_key)

    if not tenant:
        raise MCPAuthError("Invalid API key")

    if not tenant.is_active:
        raise MCPAuthError("Tenant is inactive")

    return tenant
