"""BibPdfTool — AXMTool for downloading open-access PDFs."""

from __future__ import annotations

from typing import Any

from axm.tools.base import AXMTool, ToolResult

from axm_bib.pipeline import BibPipeline

__all__ = ["BibPdfTool"]


class BibPdfTool(AXMTool):
    """Download open-access PDF for any scholarly identifier.

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

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

    def execute(self, *, ref: str = "", **kwargs: Any) -> ToolResult:
        """Download PDF, extract content, and write BibTeX.

        Args:
            ref: Any scholarly identifier (DOI, arXiv ID, HAL ID, etc.).

        Returns:
            ToolResult with full pipeline data.
        """
        if not ref.strip():
            return ToolResult(success=False, error="identifier is required")

        try:
            pipeline = BibPipeline()
            result = pipeline.download_pdf(ref)

            if result is None:
                return ToolResult(
                    success=True,
                    data={
                        "path": None,
                        "is_open_access": False,
                        "message": "Paper is not open access",
                    },
                )

            data: dict[str, Any] = {
                "path": result.path,
                "size_bytes": result.size_bytes,
                "is_open_access": True,
                "paper_dir": result.paper_dir,
                "bibtex_path": result.bibtex_path,
            }
            if result.extraction:
                data["markdown_path"] = result.extraction.markdown_path
                data["page_count"] = result.extraction.page_count
                data["char_count"] = result.extraction.char_count
                data["figure_count"] = len(result.extraction.figures)

            return ToolResult(success=True, data=data)
        except Exception as exc:
            return ToolResult(success=False, error=str(exc))
