"""API storage management tools."""

import json
from typing import Any

from mcp.types import TextContent, Tool

from maeris_mcp.storage.api_store import APIStore
from maeris_mcp.types.api import StoredAPIList


def get_stored_apis_tool() -> Tool:
    """Return the tool definition for get_stored_apis."""
    return Tool(
        name="get_stored_apis",
        description=(
            "Retrieves stored API lists. Can get all lists, a specific list by ID, "
            "or filter by project name."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "id": {
                    "type": "string",
                    "description": "Optional: specific API list ID to retrieve",
                },
                "project_name": {
                    "type": "string",
                    "description": "Optional: filter by project name",
                },
                "summary_only": {
                    "type": "boolean",
                    "description": "If true, return only summary information without full API details",
                },
            },
        },
    )


def clear_stored_apis_tool() -> Tool:
    """Return the tool definition for clear_stored_apis."""
    return Tool(
        name="clear_stored_apis",
        description=(
            "Clears stored API lists. Can clear all lists or a specific list by ID."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "id": {
                    "type": "string",
                    "description": "Optional: specific API list ID to delete. If not provided, clears all.",
                },
            },
        },
    )


async def handle_get_stored_apis(
    api_store: APIStore,
    arguments: dict,
) -> list[TextContent]:
    """Handle the get_stored_apis tool call."""
    list_id = arguments.get("id", "")
    project_name = arguments.get("project_name", "")
    summary_only = arguments.get("summary_only", False)

    result: Any

    if list_id:
        # Get specific list
        api_list = api_store.get(list_id)
        if not api_list:
            return [TextContent(type="text", text=f"Error: API list not found: {list_id}")]

        if summary_only:
            result = _build_summary_response(api_list)
        else:
            result = api_list.model_dump(by_alias=True, exclude_none=True)
    elif project_name:
        # Filter by project
        lists = api_store.find_by_project_name(project_name)
        if summary_only:
            result = [_build_summary_response(lst) for lst in lists]
        else:
            result = [lst.model_dump(by_alias=True, exclude_none=True) for lst in lists]
    else:
        # Get all
        lists = api_store.get_all()
        if summary_only:
            result = [_build_summary_response(lst) for lst in lists]
        else:
            result = [lst.model_dump(by_alias=True, exclude_none=True) for lst in lists]

    response_json = json.dumps(result, indent=2)
    return [TextContent(type="text", text=response_json)]


async def handle_clear_stored_apis(
    api_store: APIStore,
    arguments: dict,
) -> list[TextContent]:
    """Handle the clear_stored_apis tool call."""
    list_id = arguments.get("id", "")

    if list_id:
        # Delete specific list
        deleted = api_store.delete(list_id)
        response = {
            "success": deleted,
            "message": f"Deleted API list: {list_id}" if deleted else f"API list not found: {list_id}",
        }
    else:
        # Clear all
        count = api_store.clear()
        response = {
            "success": True,
            "message": f"Cleared {count} API list(s)",
            "count": count,
        }

    response_json = json.dumps(response, indent=2)
    return [TextContent(type="text", text=response_json)]


def _build_summary_response(api_list: StoredAPIList) -> dict:
    """Create a summary response for a single API list."""
    result: dict[str, Any] = {
        "id": api_list.id,
        "name": api_list.name,
        "storedAt": api_list.stored_at,
        "lastAccessed": api_list.last_accessed,
    }

    if api_list.collection:
        result["projectName"] = api_list.collection.project_name
        result["summary"] = api_list.collection.summary.model_dump(by_alias=True)
        result["apiCount"] = len(api_list.collection.apis)
        result["httpClients"] = api_list.collection.http_clients

    return result
