"""
Tool registry for Amina CLI.

Provides endpoint resolution for tool execution.
All tool metadata now lives in commands/tools/ files.

Environment variables:
- AMINA_USE_DEV_ENDPOINTS: Set to "1" to use Modal dev endpoints (for local testing)
- AMINA_ENDPOINT_OVERRIDE: Override specific tool endpoint (format: "tool_name=url")
- AMINA_GATEWAY_URL: Override the gateway URL (for testing)
"""

import os

# CLI Gateway endpoints (unified entry point for all tools)
# The gateway provides submit_tool and job_status endpoints
GATEWAY_BASE_URL = os.environ.get(
    "AMINA_GATEWAY_URL",
    "https://aminoanalytica--cli-gateway-api",
)

# Check if using dev endpoints (set AMINA_USE_DEV_ENDPOINTS=1 for local testing with modal serve)
USE_DEV_ENDPOINTS = os.environ.get("AMINA_USE_DEV_ENDPOINTS", "").lower() in ("1", "true", "yes")


class ToolNotFoundError(Exception):
    """Raised when a tool is not found."""

    pass


def _get_gateway_base() -> str:
    """Get the gateway base URL, applying dev endpoint conversion if needed."""
    base = GATEWAY_BASE_URL
    if USE_DEV_ENDPOINTS:
        # For modal deploy --env dev: aminoanalytica-dev--app-name
        base = base.replace("aminoanalytica--", "aminoanalytica-dev--")
    return base


def get_submit_endpoint(tool_name: str) -> str:
    """
    Get the submit_tool endpoint URL for a tool.

    Args:
        tool_name: Tool name (e.g., "esmfold", "pdb-cleaner")

    Returns:
        Submit endpoint URL with tool_name query parameter

    Raises:
        ToolNotFoundError: If tool not found
    """
    # Verify tool exists
    get_tool(tool_name)

    base = _get_gateway_base()
    return f"{base}-submit-tool.modal.run?tool_name={tool_name}"


def get_status_endpoint() -> str:
    """
    Get the job_status endpoint URL.

    Returns:
        Status polling endpoint URL (call_id added as query param by client)
    """
    base = _get_gateway_base()
    return f"{base}-job-status.modal.run"


def get_queued_status_endpoint() -> str:
    """
    Get the queued_job_status endpoint URL.

    Returns:
        Queued job status polling endpoint URL (job_id added as query param by client)
    """
    base = _get_gateway_base()
    return f"{base}-queued-job-status.modal.run"


# Legacy function for backwards compatibility
def get_tool_endpoint(name: str) -> str:
    """
    Get the gateway endpoint URL for a tool.

    DEPRECATED: Use get_submit_endpoint() and get_status_endpoint() instead.

    This function is kept for backwards compatibility but now returns
    the submit endpoint.

    Args:
        name: Tool name

    Returns:
        Gateway endpoint URL with tool_name query parameter

    Raises:
        ToolNotFoundError: If tool not found
    """
    # Check for specific endpoint override first
    override = os.environ.get("AMINA_ENDPOINT_OVERRIDE", "")
    if override and "=" in override:
        override_name, override_url = override.split("=", 1)
        if override_name == name:
            return override_url

    return get_submit_endpoint(name)


def get_all_tools() -> list[dict]:
    """Get all available tools."""
    from amina_cli.commands.tools import get_all_tools as _get_all_tools

    return _get_all_tools()


def get_tool(name: str) -> dict:
    """
    Get a specific tool by name.

    Args:
        name: Tool name (e.g., "esmfold", "pdb-cleaner")

    Returns:
        Tool METADATA dictionary

    Raises:
        ToolNotFoundError: If tool not found
    """
    from amina_cli.commands.tools import get_tool as _get_tool

    tool = _get_tool(name)
    if not tool:
        raise ToolNotFoundError(f"Tool '{name}' not found. Run 'amina tools' to see available tools.")
    return tool


def get_tools_by_category(category: str) -> list[dict]:
    """
    Get all tools in a specific category.

    Args:
        category: Category name (e.g., "folding", "utilities")

    Returns:
        List of tool definitions in that category
    """
    tools = get_all_tools()
    return [t for t in tools if t.get("category") == category]


def get_categories() -> list[str]:
    """
    Get all available categories.

    Returns:
        Sorted list of unique category names
    """
    tools = get_all_tools()
    categories = set(t.get("category", "other") for t in tools)
    return sorted(categories)


def search_tools(query: str) -> list[dict]:
    """
    Search tools by name or description.

    Args:
        query: Search query

    Returns:
        List of matching tools
    """
    query_lower = query.lower()
    tools = get_all_tools()
    return [
        t
        for t in tools
        if query_lower in t["name"].lower()
        or query_lower in t.get("description", "").lower()
        or query_lower in t.get("display_name", "").lower()
    ]
