"""Find tool — glob-based file search."""

from __future__ import annotations

import glob as globmod
import os
from typing import Any

from pi_agents.agent.types import AgentTool, AgentToolResult
from pi_agents.ai.types import TextContent
from pi_agents.coding_agent.tools.truncate import truncate_head


FIND_TOOL_NAME = "find"
FIND_TOOL_DESCRIPTION = "Find files matching a glob pattern."

FIND_TOOL_PARAMETERS = {
    "type": "object",
    "properties": {
        "pattern": {"type": "string", "description": "Glob pattern (e.g. '*.ts', '**/*.json')"},
        "path": {"type": "string", "description": "Directory to search in"},
        "limit": {"type": "integer", "description": "Max results (default: 1000)"},
    },
    "required": ["pattern"],
}


def create_find_tool(cwd: str | None = None) -> AgentTool:
    """Create a find tool for glob-based file search."""

    class FindTool(AgentTool):
        def __init__(self) -> None:
            super().__init__(
                name=FIND_TOOL_NAME,
                description=FIND_TOOL_DESCRIPTION,
                parameters=FIND_TOOL_PARAMETERS,
            )
            self.label = "Find"

        async def execute(
            self,
            tool_call_id: str,
            params: dict[str, Any],
            signal: Any = None,
            on_update: Any = None,
        ) -> AgentToolResult:
            pattern = params.get("pattern", "")
            search_path = params.get("path", "")
            limit = params.get("limit", 1000)

            base = search_path or cwd or os.getcwd()
            if cwd and not os.path.isabs(base):
                base = os.path.join(cwd, base)

            full_pattern = os.path.join(base, pattern)
            matches = globmod.glob(full_pattern, recursive=True)
            matches.sort()

            # Make paths relative
            rel_paths: list[str] = []
            for m in matches[:limit]:
                try:
                    rel = os.path.relpath(m, base).replace("\\", "/")
                    rel_paths.append(rel)
                except ValueError:
                    rel_paths.append(m.replace("\\", "/"))

            result = "\n".join(rel_paths)
            tr = truncate_head(result)

            return AgentToolResult(
                content=[TextContent(type="text", text=tr.content or "(no matches)")]
            )

    return FindTool()
