"""Utility tools for Crustdata MCP Server."""

from typing import Optional

from mcp.server.fastmcp import Context
from pydantic import BaseModel, Field, field_validator

from ..client import CrustdataAPIError, CrustdataAuthError
from ..client_factory import get_client_for_request
from ..models.common import LinkedinAutocompleteFilterType
from ..server import AppContext, mcp


@mcp.tool(
    name="crustdata_credits_check",
    description="Check your current Crustdata API credit balance and account tier.",
)
async def crustdata_credits_check(ctx: Context[None, AppContext, None]) -> dict:
    """Check remaining API credits.

    Returns information about your current credit balance and account tier.
    Use this to monitor your API usage before making requests.

    Returns:
        A dictionary containing:
        - credits: Current credit balance
        - tier: Account tier (e.g., 'professional', 'enterprise')
        - Additional account information if available
    """
    client = get_client_for_request()

    try:
        result = await client.get("/user/credits")
        ctx.info(f"Credits check successful: {result.get('credits', 'N/A')} credits")
        return result
    except CrustdataAuthError as e:
        ctx.error(f"Authentication failed: {e}")
        raise
    except CrustdataAPIError as e:
        ctx.error(f"API error: {e}")
        raise


# =============================================================================
# LinkedIn Filter Autocomplete - GET /screener/linkedin_filter/autocomplete
# =============================================================================


class LinkedInFilterAutocompleteInput(BaseModel):
    """Input parameters for LinkedIn filter autocomplete suggestions."""

    filter_type: str = Field(
        ...,
        description="Type of filter to get suggestions for. Valid values: 'region', 'industry', 'title', 'school'.",
    )
    query: str = Field(
        ...,
        description="Search query for autocomplete suggestions (e.g., 'San' for regions, 'Tech' for industries).",
    )
    count: Optional[int] = Field(
        10,
        ge=1,
        le=50,
        description="Maximum number of suggestions to return (default: 10, max: 50).",
    )
    start: Optional[int] = Field(
        0,
        ge=0,
        description="Starting index for pagination (offset-based).",
    )

    @field_validator("filter_type")
    @classmethod
    def validate_filter_type(cls, v: str) -> str:
        """Validate filter_type against allowed enum values."""
        try:
            # Validate against the enum
            LinkedinAutocompleteFilterType(v)
        except ValueError:
            valid_types = [t.value for t in LinkedinAutocompleteFilterType]
            raise ValueError(
                f"Invalid filter_type: '{v}'. Must be one of: {', '.join(valid_types)}"
            )
        return v


@mcp.tool(
    name="crustdata_autocomplete_linkedin_filter",
    description="Get autocomplete suggestions for LinkedIn filter values. "
    "Useful for building valid filters for people and company searches. "
    "Supports 'region', 'industry', 'title', and 'school' filter types.",
)
async def crustdata_autocomplete_linkedin_filter(
    params: LinkedInFilterAutocompleteInput,
    ctx: Context[None, AppContext, None],
) -> list[str]:
    """Get autocomplete suggestions for LinkedIn filters.

    This helps users discover valid filter values for people and company
    search filters. Supports REGION, INDUSTRY, TITLE, and SCHOOL filter types.

    Args:
        params: Autocomplete parameters including filter_type and query.
        ctx: MCP context for logging and client access.

    Returns:
        List of autocomplete suggestion strings.
    """
    client = get_client_for_request()

    query_params: dict = {
        "filter_type": params.filter_type,
        "query": params.query,
    }
    if params.count is not None:
        query_params["count"] = params.count
    if params.start is not None:
        query_params["start"] = params.start

    try:
        ctx.info(f"Getting LinkedIn filter autocomplete for {params.filter_type}: '{params.query}'")
        result = await client.get("/screener/linkedin_filter/autocomplete", params=query_params)

        suggestions = result.get("results", [])
        ctx.info(f"Found {len(suggestions)} suggestions")
        return suggestions

    except CrustdataAuthError as e:
        ctx.error(f"Authentication failed: {e}")
        raise
    except CrustdataAPIError as e:
        ctx.error(f"API error: {e}")
        raise
