"""DataEyes reader tool."""

from pydantic import BaseModel, Field

from dataeyes_mcp_server.server import mcp, send_request


class ReaderRequest(BaseModel):
    """Reader request parameters."""

    url: str = Field(description="Target web page URL")
    timeout: int | None = Field(default=None, description="Timeout in seconds")
    format: str | None = Field(default=None, description="Output format: markdown, html, both (default: markdown)")
    noStore: int | None = Field(default=None, description="0=store response (default), 1=do not store")
    maxAge: int | None = Field(default=None, description="Max cache age in seconds. 0=no cache")
    headers: dict[str, str] | None = Field(default=None, description="Custom request headers (cookies, user-agent, etc.)")
    sanitization: str | None = Field(default=None, description="Content sanitization mode: clean, raw")
    proxyPlan: str | None = Field(default=None, description="Proxy plan: basic, plus")
    proxyURL: str | None = Field(default=None, description="Custom proxy URL")


class ReaderMetadata(BaseModel):
    """Metadata about the fetched page."""

    url: str = Field(default="", description="Final URL after redirects")
    title: str = Field(default="", description="Page title")
    description: str = Field(default="", description="Meta description")
    keywords: str = Field(default="", description="Meta keywords")
    siteName: str = Field(default="", description="Website name")
    favicon: str = Field(default="", description="Favicon URL")
    statusCode: int = Field(default=0, description="HTTP status code")
    contentType: str = Field(default="", description="Content-Type header")
    cached: int = Field(default=0, description="1 if served from cache")


class ReaderResponse(BaseModel):
    """Structured reader response."""

    metadata: ReaderMetadata = Field(default_factory=ReaderMetadata, description="Page metadata")
    html: str = Field(default="", description="HTML content")
    markdown: str = Field(default="", description="Markdown content")


@mcp.tool(
    name="read",
    annotations={
        "title": "Web Reader",
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": True,
    },
)
async def read(params: ReaderRequest) -> ReaderResponse:
    """Read and extract content from a web page URL.

    Fetches the page, extracts the main content, and returns it in the
    requested format (markdown by default). Includes metadata such as
    title, description, and status code.
    """
    payload = params.model_dump(exclude_none=True)
    req_timeout = float(params.timeout) + 10 if params.timeout else 60.0
    data = await send_request("/v1/reader", payload=payload, timeout=req_timeout)
    return ReaderResponse(**data)
