#!/usr/bin/env python3
"""
Cluster management tools for CAST.AI External MCP Server.

Provides tools for listing clusters, getting cluster details, scores, and history.
"""

import json

from fastmcp import FastMCP

from src.cache import resolve_cluster_id
from src.client import make_request


def register_cluster_tools(mcp: FastMCP):
    """Register all cluster-related MCP tools."""

    @mcp.tool()
    async def list_clusters() -> str:
        """
        List all Kubernetes external clusters.

        Returns:
            JSON string with list of clusters
        """
        try:
            result = await make_request("GET", "/v1/kubernetes/external-clusters")
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({"error": str(e)})

    @mcp.tool()
    async def get_cluster_details(cluster_id_or_name: str) -> str:
        """
        Get detailed information about a specific cluster.

        Args:
            cluster_id_or_name: The cluster ID (UUID) or cluster name

        Returns:
            JSON string with cluster details
        """
        try:
            cluster_id = await resolve_cluster_id(cluster_id_or_name)
            result = await make_request("GET", f"/v1/kubernetes/external-clusters/{cluster_id}")
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({"error": str(e)})

    @mcp.tool()
    async def get_cluster_score(cluster_id_or_name: str) -> str:
        """
        Get the cluster score (optimization scorecard).

        The cluster score provides metrics on cost optimization, efficiency,
        and best practices for the cluster.

        Args:
            cluster_id_or_name: The cluster ID (UUID) or cluster name

        Returns:
            JSON string with cluster score data
        """
        try:
            cluster_id = await resolve_cluster_id(cluster_id_or_name)
            result = await make_request("GET", f"/v1/cost-reports/clusters/{cluster_id}/cluster-score")
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({"error": str(e)})

    @mcp.tool()
    async def get_cluster_score_history(cluster_id_or_name: str) -> str:
        """
        Get the historical cluster score data.

        Shows how the cluster score has changed over time.

        Args:
            cluster_id_or_name: The cluster ID (UUID) or cluster name

        Returns:
            JSON string with cluster score history
        """
        try:
            cluster_id = await resolve_cluster_id(cluster_id_or_name)
            result = await make_request("GET", f"/v1/cost-reports/clusters/{cluster_id}/cluster-score-history")
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({"error": str(e)})
