"""Dataset tools for Crustdata MCP Server."""

from typing import Optional

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

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


class JobListingsInput(BaseModel):
    """Input parameters for job listings query."""

    filters: dict = Field(
        ...,
        description="""Filters for job listings. Can be simple or complex nested conditions.

Simple filter example:
{"filter_type": "title", "type": "(.)", "value": "Software Engineer"}

Complex AND filter example:
{
    "op": "AND",
    "conditions": [
        {"filter_type": "company_name", "type": "(.)", "value": "Google"},
        {"filter_type": "location", "type": "(.)", "value": "San Francisco"}
    ]
}

Available filter fields:
- title: Job title
- company_name: Company name
- company_id: Crustdata company ID
- location: Job location
- description: Job description text
- posted_date: When the job was posted
""",
    )
    limit: int = Field(
        20,
        ge=1,
        le=1000,
        description="Number of results to return (default: 20, max: 1000).",
    )
    cursor: Optional[str] = Field(
        None,
        description="Pagination cursor from previous response.",
    )
    sorts: Optional[list[dict]] = Field(
        None,
        description='Sort options. Example: [{"column": "posted_date", "order": "desc"}]',
    )


@mcp.tool(
    name="crustdata_dataset_job_listings",
    description="Query the job listings dataset. Search for job postings by company, "
    "title, location, and more. Useful for market research and hiring trend analysis.",
)
async def crustdata_dataset_job_listings(
    params: JobListingsInput,
    ctx: Context[None, AppContext, None],
) -> dict:
    """Query job listings dataset.

    Args:
        params: Job listings query parameters.
        ctx: MCP context for logging and client access.

    Returns:
        Dictionary with:
        - job_listings: List of matching job postings
        - total_count: Total number of matches
        - next_cursor: Cursor for fetching next page
    """
    client = get_client_for_request()

    data: dict = {"filters": params.filters, "limit": params.limit}
    if params.cursor:
        data["cursor"] = params.cursor
    if params.sorts:
        data["sorts"] = params.sorts

    try:
        ctx.info(f"Querying job listings with filters: {params.filters}")
        result = await client.post("/data_lab/job_listings/Table/", data=data)

        listings = result.get("job_listings", result.get("data", []))
        ctx.info(f"Found {len(listings)} job listings")
        return {
            "job_listings": listings,
            "total_count": result.get("total_count"),
            "next_cursor": result.get("next_cursor"),
        }

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