"""BibSearchTool — AXMTool for searching papers by title."""

from __future__ import annotations

from typing import Any

from axm.tools.base import AXMTool, ToolResult

from axm_bib.pipeline import BibPipeline

__all__ = ["BibSearchTool"]


class BibSearchTool(AXMTool):
    """Search papers by title/keywords, return structured metadata + DOI.

    Registered as 'bib_search' via axm.tools entry point.
    """

    @property
    def name(self) -> str:
        """Return the tool name used for entry-point registration."""
        return "bib_search"

    def execute(self, *, query: str = "", limit: int = 5, **kwargs: Any) -> ToolResult:
        """Search papers by title.

        Args:
            query: Search query string.
            limit: Maximum number of results.

        Returns:
            ToolResult with data={"papers": [...]}.
        """
        if limit < 1:
            return ToolResult(success=False, error=f"limit must be ≥ 1, got {limit}")
        try:
            pipeline = BibPipeline()
            papers = pipeline.search(query, limit=limit)
            return ToolResult(
                success=True,
                data={
                    "papers": [p.model_dump() for p in papers],
                    "count": len(papers),
                },
            )
        except Exception as exc:
            return ToolResult(success=False, error=str(exc))
