#!/usr/bin/env python3
"""
Caching utilities for CAST.AI External MCP Server.

Handles cluster name resolution caching.
"""

from src.client import make_request
from src.logger import logger


# Cache for cluster name to ID mapping
_cluster_cache: dict[str, str] | None = None


async def resolve_cluster_id(cluster_id_or_name: str) -> str:
    """
    Resolve cluster name to cluster ID.

    If the input is already a UUID, return it as-is.
    If it's a cluster name, look it up and return the ID.

    Args:
        cluster_id_or_name: Either a cluster ID (UUID) or cluster name

    Returns:
        The cluster ID (UUID)

    Raises:
        Exception if cluster not found
    """
    global _cluster_cache

    # Check if it's already a UUID (contains hyphens and is 36 chars)
    if len(cluster_id_or_name) == 36 and cluster_id_or_name.count("-") == 4:
        return cluster_id_or_name

    # Load cluster cache if not loaded
    if _cluster_cache is None:
        try:
            logger.debug("Loading cluster cache")
            result = await make_request("GET", "/v1/kubernetes/external-clusters")
            _cluster_cache = {}
            for cluster in result.get("items", []):
                cluster_id = cluster.get("id")
                cluster_name = cluster.get("name")
                if cluster_id and cluster_name:
                    _cluster_cache[cluster_name] = cluster_id
            logger.info("Cluster cache loaded", cluster_count=len(_cluster_cache))
        except Exception as e:
            logger.error("Failed to load cluster cache", error=str(e))
            raise Exception(f"Failed to load cluster list: {e}") from e

    # Look up by name
    if cluster_id_or_name in _cluster_cache:
        return _cluster_cache[cluster_id_or_name]

    raise Exception(f"Cluster not found: {cluster_id_or_name}. Use cluster ID (UUID) or exact cluster name.")
