"""DataEyes search tool."""

from pydantic import BaseModel, Field

from dataeyes_mcp_server.server import mcp, send_request


class SearchRequest(BaseModel):
    """Search request parameters."""

    q: str = Field(description="Search query keywords")
    num: int | None = Field(default=None, description="Number of results to return (max 50)", ge=1, le=50)
    range: str | None = Field(default=None, description="Time range filter: day, week, month, year")
    fileType: str | None = Field(default=None, description="File type filter: pdf, doc, xls, ppt, rtf")
    includeSite: list[str] | None = Field(default=None, description="Restrict results to these domains")
    excludeSite: list[str] | None = Field(default=None, description="Exclude results from these domains")


class WebPage(BaseModel):
    """A single search result."""

    name: str = Field(description="Page title")
    url: str = Field(description="Page URL")
    snippet: str = Field(default="", description="Text snippet / summary")
    score: int = Field(default=0, description="Relevance score")
    displayUrl: str = Field(default="", description="Display URL")
    siteName: str = Field(default="", description="Website name")
    siteIcon: str = Field(default="", description="Website favicon URL")
    datePublished: str = Field(default="", description="Publication date")


class SearchResponse(BaseModel):
    """Structured search response."""

    originalQuery: str = Field(description="The original search query")
    webPages: list[WebPage] = Field(default_factory=list, description="List of search results")


@mcp.tool(
    name="search",
    annotations={
        "title": "Web Search",
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": True,
    },
)
async def search(params: SearchRequest) -> SearchResponse:
    """Search the web using DataEyes search engine.

    Returns a list of web page results including title, URL, snippet,
    and relevance score. Useful for finding information, research,
    and discovering relevant web pages on any topic.
    """
    payload = params.model_dump(exclude_none=True)
    data = await send_request("/v1/search", payload=payload)
    return SearchResponse(**data)
