"""BibExtractTool — AXMTool for extracting PDF content to Markdown + figures."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from axm.tools.base import AXMTool, ToolResult

from axm_bib.extract import extract_pdf

__all__ = ["BibExtractTool"]


class BibExtractTool(AXMTool):
    """Extract PDF content to Markdown + figure PNGs.

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

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

    def execute(
        self, *, pdf_path: str = "", output_dir: str = "", **kwargs: Any
    ) -> ToolResult:
        """Extract PDF content.

        Args:
            pdf_path: Path to the PDF file.
            output_dir: Output directory (optional).

        Returns:
            ToolResult with extraction metadata.
        """
        if not pdf_path.strip():
            return ToolResult(success=False, error="pdf_path is required")

        try:
            out = Path(output_dir) if output_dir.strip() else None
            result = extract_pdf(Path(pdf_path), out)

            return ToolResult(
                success=True,
                data={
                    "output_dir": result.output_dir,
                    "markdown_path": result.markdown_path,
                    "page_count": result.page_count,
                    "word_count": result.word_count,
                    "char_count": result.char_count,
                    "figure_count": len(result.figures),
                    "figures": [
                        {"filename": f.filename, "page": f.page} for f in result.figures
                    ],
                },
            )
        except Exception as exc:
            return ToolResult(success=False, error=str(exc))
