#!/usr/bin/env python3
"""
Cost and savings analysis tools for CAST.AI External MCP Server.

Provides tools for cost reports, savings reports, and workload efficiency analysis.
"""

import json

from fastmcp import FastMCP

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


def register_cost_tools(mcp: FastMCP):
    """Register all cost and savings related MCP tools."""

    @mcp.tool()
    async def get_cost_report(
        cluster_id_or_name: str,
        start_time: str,
        end_time: str,
        aggregate_by: str = "day",
    ) -> str:
        """
        Get cost report for a cluster over a time period.

        Shows cluster costs aggregated by day, hour, or month. Use this to analyze
        spending patterns, track costs over time, and identify cost trends.

        Args:
            cluster_id_or_name: The cluster ID (UUID) or cluster name
            start_time: Start time in RFC3339 format (e.g., "2024-01-01T00:00:00Z")
            end_time: End time in RFC3339 format (e.g., "2024-01-31T23:59:59Z")
            aggregate_by: Aggregation period - "day" (default), "hour", or "month"

        Returns:
            JSON string with cost data including total costs, breakdown by resource type,
            and costs over time based on aggregation period
        """
        try:
            cluster_id = await resolve_cluster_id(cluster_id_or_name)
            result = await make_request(
                "GET",
                f"/v1/cost-reports/clusters/{cluster_id}/cost",
                params={
                    "startTime": start_time,
                    "endTime": end_time,
                    "aggregateBy": aggregate_by,
                },
            )
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({"error": str(e)})

    @mcp.tool()
    async def get_workload_efficiency(
        cluster_id_or_name: str,
        start_time: str,
        end_time: str,
    ) -> str:
        """
        Get workload efficiency analysis for a cluster.

        Analyzes how efficiently workloads are using their allocated resources.
        Shows CPU and memory utilization vs requests, helping identify overprovisioned
        workloads and optimization opportunities.

        Args:
            cluster_id_or_name: The cluster ID (UUID) or cluster name
            start_time: Start time in RFC3339 format (e.g., "2024-01-01T00:00:00Z")
            end_time: End time in RFC3339 format (e.g., "2024-01-31T23:59:59Z")

        Returns:
            JSON string with workload efficiency data including utilization metrics,
            waste analysis, and efficiency scores
        """
        try:
            cluster_id = await resolve_cluster_id(cluster_id_or_name)
            result = await make_request(
                "GET",
                f"/v1/cost-reports/clusters/{cluster_id}/workload-efficiency",
                params={
                    "startTime": start_time,
                    "endTime": end_time,
                },
            )
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({"error": str(e)})

    @mcp.tool()
    async def get_savings_report(
        cluster_id_or_name: str,
        start_time: str,
        end_time: str,
    ) -> str:
        """
        Get savings report for a cluster showing CAST.AI cost optimizations.

        Shows both actual savings achieved and estimated potential savings from
        CAST.AI's optimization features. This demonstrates the ROI of using CAST.AI
        for cluster management and cost optimization.

        Args:
            cluster_id_or_name: The cluster ID (UUID) or cluster name
            start_time: Start time in RFC3339 format (e.g., "2024-01-01T00:00:00Z")
            end_time: End time in RFC3339 format (e.g., "2024-01-31T23:59:59Z")

        Returns:
            JSON string with savings data including actual savings, estimated savings,
            savings by feature (autoscaling, spot instances, bin packing, etc.),
            and savings trends over time
        """
        try:
            cluster_id = await resolve_cluster_id(cluster_id_or_name)
            result = await make_request(
                "GET",
                f"/v1/cost-reports/clusters/{cluster_id}/savings",
                params={
                    "startTime": start_time,
                    "endTime": end_time,
                },
            )
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({"error": str(e)})