"""Request-related tools for Zip MCP."""

from typing import Any, Literal

import httpx

from src.app import get_api_key, mcp  # pyright: ignore[reportUnknownVariableType]

from .common import get_headers

BASE_REQUESTS_URL = f"{BASE_URL}/requests"


@mcp.tool()
async def zip_search_requests(
    request_number: str | None = None,
    status: int | None = None,
    priority: int | None = None,
    requester_id: str | None = None,
    requester_name: str | None = None,
    request_type: Literal[
        "PURCHASE_REQUEST",
        "SECURITY_REVIEW",
        "VENDOR_ONBOARDING",
        "SOURCING_REQUEST",
        "PO_CHANGE_ORDER",
    ]
    | None = None,
    department_name: str | None = None,
    department_id: list[str] | None = None,
    vendor_name: str | None = None,
    vendor_id: str | None = None,
    created_after: int | None = None,
    created_before: int | None = None,
    completed_after: int | None = None,
    completed_before: int | None = None,
    last_updated_after: int | None = None,
    last_updated_before: int | None = None,
    include_attributes: bool | None = None,
    sort_by: Literal[
        "create_time",
        "complete_time",
        "last_updated_time",
        "request_number",
        "status",
    ]
    | None = None,
    sort_order: Literal["asc", "desc"] | None = None,
    page_size: int | None = None,
    page_token: str | None = None,
) -> str:
    """Search for purchase requests in Zip. The list of results is capped at 30.

    Args:
        request_number: The request number in Zip (e.g. "1234")
        status: The status of the request. 1=AWAITING_APPROVAL, 2=REJECTED,
            3=APPROVED, 4=CANCELED, 5=CLOSED, 6=PAUSED
        priority: The priority of the request. 0=Urgent, 1=Normal
        requester_id: User ID (UUID) of the requester
        requester_name: Requester name
        request_type: Request type (PURCHASE_REQUEST, SECURITY_REVIEW,
            VENDOR_ONBOARDING, SOURCING_REQUEST, PO_CHANGE_ORDER)
        department_name: Name of the department attached to the request
        department_id: List of department IDs (UUIDs) attached to the request
        vendor_name: Name of the vendor attached to the request
        vendor_id: ID (UUID) of the vendor attached to the request
        created_after: Query requests created after this epoch timestamp (seconds)
        created_before: Query requests created before this epoch timestamp (seconds)
        completed_after: Query requests completed after this epoch timestamp (seconds)
        completed_before: Query requests completed before this epoch timestamp (seconds)
        last_updated_after: Query requests updated after this epoch timestamp (seconds)
        last_updated_before: Query requests updated before this epoch timestamp (seconds)
        include_attributes: Include custom fields in the response (increases latency)
        sort_by: Sort requests by a property (create_time, complete_time,
            last_updated_time, request_number, status)
        sort_order: Sort order (asc, desc)
        page_size: Number of results per page
        page_token: Pagination token for next page
    """

    # Build query parameters, filtering out None values
    params: dict[str, Any] = {
        "request_number": request_number,
        "status": status,
        "priority": priority,
        "requester_id": requester_id,
        "requester_name": requester_name,
        "request_type": request_type,
        "department_name": department_name,
        "department_id": department_id,
        "vendor_name": vendor_name,
        "vendor_id": vendor_id,
        "created_after": created_after,
        "created_before": created_before,
        "completed_after": completed_after,
        "completed_before": completed_before,
        "last_updated_after": last_updated_after,
        "last_updated_before": last_updated_before,
        "include_attributes": include_attributes,
        "sort_by": sort_by,
        "sort_order": sort_order,
        "page_size": page_size,
        "page_token": page_token,
    }
    params = {k: v for k, v in params.items() if v is not None}

    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{BASE_REQUESTS_URL}/requests", headers=get_headers(), params=params
        )
        return response.text


@mcp.tool()
async def zip_get_request(request_id: str) -> str:
    """Get details of a specific purchase request by ID.

    Args:
        request_id: The unique identifier (UUID) of the purchase request.
    """
    if not api_key:
        return "Error: ZIP_API_KEY not configured."

    url = f"{BASE_REQUESTS_URL}/requests/{request_id}"

    async with httpx.AsyncClient() as client:
        response = await client.get(url, headers=get_headers())
        return response.text
