"""Arcade Starter Tools for Cursor_Agents

DO NOT EDIT THIS MODULE DIRECTLY.

THIS MODULE WAS AUTO-GENERATED BY TRANSPILING THE API STARTER TOOL JSON DEFINITIONS
IN THE ../wrapper_tools DIRECTORY INTO PYTHON CODE. ANY CHANGES TO THIS MODULE WILL
BE OVERWRITTEN BY THE TRANSPILER.
"""

import asyncio
from typing import Annotated, Any

import httpx
from arcade_tdk import ToolContext, tool

# Retry configuration
INITIAL_RETRY_DELAY = 0.5  # seconds

HTTP_CLIENT = httpx.AsyncClient(
    timeout=httpx.Timeout(60.0, connect=10.0),
    limits=httpx.Limits(max_keepalive_connections=20, max_connections=100),
    transport=httpx.AsyncHTTPTransport(retries=3),
    http2=True,
    follow_redirects=True,
)


def remove_none_values(data: dict[str, Any]) -> dict[str, Any]:
    return {k: v for k, v in data.items() if v is not None}


async def make_request(
    url: str,
    method: str,
    params: dict[str, Any] | None = None,
    headers: dict[str, Any] | None = None,
    data: dict[str, Any] | None = None,
    auth: tuple[str, str] | None = None,
    max_retries: int = 3,
) -> httpx.Response:
    """Make an HTTP request with retry logic for 5xx server errors."""
    for attempt in range(max_retries):
        try:
            response = await HTTP_CLIENT.request(
                url=url,
                auth=auth,
                method=method,
                params=params,
                headers=headers,
                data=data,
            )
            response.raise_for_status()
        except httpx.HTTPStatusError as e:
            # Only retry on 5xx server errors
            if e.response.status_code >= 500 and attempt < max_retries - 1:
                # Exponential backoff: 0.5s, 1s, 2s
                await asyncio.sleep(INITIAL_RETRY_DELAY * (2**attempt))
                continue
            # Re-raise for 4xx errors or if max retries reached
            raise
        except httpx.RequestError:
            # Don't retry request errors (network issues are handled by transport)
            raise
        else:
            return response

    # This should never be reached, but satisfies type checker
    raise httpx.RequestError("Max retries exceeded")  # noqa: TRY003


@tool(requires_secrets=["CURSOR_AGENTS_API_KEY"])
async def list_background_agents(
    context: ToolContext,
    agent_limit: Annotated[
        int | None, "Number of background agents to return for the request."
    ] = 20,
    pagination_cursor: Annotated[
        str | None, "Pagination cursor from the previous response to navigate pages."
    ] = None,
) -> Annotated[dict[str, Any], "Response from the API endpoint 'listAgents'."]:
    """List all background agents for the user.

    Use this tool to retrieve a list of all background agents associated with the authenticated user."""  # noqa: E501
    response = await make_request(
        url="https://api.cursor.com/v0/agents",
        method="GET",
        params=remove_none_values({"limit": agent_limit, "cursor": pagination_cursor}),
        headers=remove_none_values({
            "Authorization": "Bearer {authorization}".format(
                authorization=context.get_secret("CURSOR_AGENTS_API_KEY")
            )
        }),
        data=remove_none_values({}),
    )
    try:
        return {"response_json": response.json()}
    except Exception:
        return {"response_text": response.text}


@tool(requires_secrets=["CURSOR_AGENTS_API_KEY"])
async def get_agent_status(
    context: ToolContext,
    background_agent_id: Annotated[
        str,
        "A unique identifier required to retrieve the status and results of the specified background agent.",  # noqa: E501
    ],
) -> Annotated[dict[str, Any], "Response from the API endpoint 'getAgent'."]:
    """Retrieve the current status and results of a background agent.

    Call this tool to get information about the status and results of a specific background agent by providing its ID."""  # noqa: E501
    response = await make_request(
        url="https://api.cursor.com/v0/agents/{id}".format(id=background_agent_id),  # noqa: UP032
        method="GET",
        params=remove_none_values({}),
        headers=remove_none_values({
            "Authorization": "Bearer {authorization}".format(
                authorization=context.get_secret("CURSOR_AGENTS_API_KEY")
            )
        }),
        data=remove_none_values({}),
    )
    try:
        return {"response_json": response.json()}
    except Exception:
        return {"response_text": response.text}


@tool(requires_secrets=["CURSOR_AGENTS_API_KEY"])
async def delete_background_agent(
    context: ToolContext,
    background_agent_id: Annotated[
        str, "Unique identifier for the background agent to be deleted permanently."
    ],
) -> Annotated[dict[str, Any], "Response from the API endpoint 'deleteAgent'."]:
    """Permanently delete a background agent.

    This tool is used to permanently delete a background agent. This action cannot be undone, so it should be called with caution when you need to remove an agent completely."""  # noqa: E501
    response = await make_request(
        url="https://api.cursor.com/v0/agents/{id}".format(id=background_agent_id),  # noqa: UP032
        method="DELETE",
        params=remove_none_values({}),
        headers=remove_none_values({
            "Authorization": "Bearer {authorization}".format(
                authorization=context.get_secret("CURSOR_AGENTS_API_KEY")
            )
        }),
        data=remove_none_values({}),
    )
    try:
        return {"response_json": response.json()}
    except Exception:
        return {"response_text": response.text}


@tool(requires_secrets=["CURSOR_AGENTS_API_KEY"])
async def get_agent_conversation_history(
    context: ToolContext,
    background_agent_id: Annotated[
        str, "Unique identifier for the background agent to retrieve conversation history."
    ],
) -> Annotated[dict[str, Any], "Response from the API endpoint 'getAgentConversation'."]:
    """Retrieve the conversation history of a background agent.

    This tool retrieves the full conversation history, including user prompts and assistant responses, for a specified background agent. It is useful for reviewing past interactions and understanding agent behavior."""  # noqa: E501
    response = await make_request(
        url="https://api.cursor.com/v0/agents/{id}/conversation".format(id=background_agent_id),  # noqa: UP032
        method="GET",
        params=remove_none_values({}),
        headers=remove_none_values({
            "Authorization": "Bearer {authorization}".format(
                authorization=context.get_secret("CURSOR_AGENTS_API_KEY")
            )
        }),
        data=remove_none_values({}),
    )
    try:
        return {"response_json": response.json()}
    except Exception:
        return {"response_text": response.text}


@tool(requires_secrets=["CURSOR_AGENTS_API_KEY"])
async def retrieve_api_user_info(
    context: ToolContext,
) -> Annotated[dict[str, Any], "Response from the API endpoint 'getMe'."]:
    """Retrieve information about the API key used for authentication.

    This tool calls the endpoint to get details regarding the API key currently in use, including any relevant user information. It should be called when there is a need to verify or display details about the authentication being used."""  # noqa: E501
    response = await make_request(
        url="https://api.cursor.com/v0/me",
        method="GET",
        params=remove_none_values({}),
        headers=remove_none_values({
            "Authorization": "Bearer {authorization}".format(
                authorization=context.get_secret("CURSOR_AGENTS_API_KEY")
            )
        }),
        data=remove_none_values({}),
    )
    try:
        return {"response_json": response.json()}
    except Exception:
        return {"response_text": response.text}


@tool(requires_secrets=["CURSOR_AGENTS_API_KEY"])
async def list_recommended_models(
    context: ToolContext,
) -> Annotated[dict[str, Any], "Response from the API endpoint 'listModels'."]:
    """Retrieve recommended models for background agents.

    Use this tool to fetch a list of models recommended for use in background agent applications."""
    response = await make_request(
        url="https://api.cursor.com/v0/models",
        method="GET",
        params=remove_none_values({}),
        headers=remove_none_values({
            "Authorization": "Bearer {authorization}".format(
                authorization=context.get_secret("CURSOR_AGENTS_API_KEY")
            )
        }),
        data=remove_none_values({}),
    )
    try:
        return {"response_json": response.json()}
    except Exception:
        return {"response_text": response.text}


@tool(requires_secrets=["CURSOR_AGENTS_API_KEY"])
async def list_github_repositories(
    context: ToolContext,
) -> Annotated[dict[str, Any], "Response from the API endpoint 'listRepositories'."]:
    """Retrieve accessible GitHub repositories for a user.

    Use this tool to get a list of GitHub repositories that the authenticated user can access. It pulls data from the user's GitHub account and returns the repositories they have permission to view or modify."""  # noqa: E501
    response = await make_request(
        url="https://api.cursor.com/v0/repositories",
        method="GET",
        params=remove_none_values({}),
        headers=remove_none_values({
            "Authorization": "Bearer {authorization}".format(
                authorization=context.get_secret("CURSOR_AGENTS_API_KEY")
            )
        }),
        data=remove_none_values({}),
    )
    try:
        return {"response_json": response.json()}
    except Exception:
        return {"response_text": response.text}
