"""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 = 10,
        venue: str | None = None,
        author: str | None = None,
        year: int | None = None,
        **kwargs: Any,
    ) -> ToolResult:
        """Search papers across all sources with optional filters.

        Args:
            query: Search query string.
            limit: Maximum number of results.
            venue: Filter by venue name (case-insensitive substring).
            author: Filter by author name (case-insensitive substring).
            year: Filter by publication year (exact match).

        Returns:
            ToolResult with data={"papers": [...], "count": N}.
        """
        if limit < 1:
            return ToolResult(success=False, error=f"limit must be ≥ 1, got {limit}")
        try:
            pipeline = BibPipeline()
            result = pipeline.search(
                query,
                limit=limit,
                venue=venue,
                author=author,
                year=year,
            )
            return ToolResult(
                success=True,
                data={
                    "papers": [p.model_dump() for p in result.papers],
                    "count": len(result.papers),
                    "sources_queried": result.sources_queried,
                    "sources_failed": result.sources_failed,
                },
                hint=(
                    "Tip: Use bib_resolve(ref) for BibTeX, "
                    "or bib_pdf(doi) for full text."
                ),
            )
        except Exception as exc:
            return ToolResult(success=False, error=str(exc))
