"""Glob search tool — find files by pattern."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from tsumugi.tools.base import BaseTool, PermissionLevel, ToolSpec


class GlobSearchTool(BaseTool):
    """Find files matching a glob pattern."""

    def spec(self) -> ToolSpec:
        return ToolSpec(
            name="glob_search",
            description=(
                'Find files matching a glob pattern (e.g. "**/*.py", "src/**/*.ts"). '
                "Returns matching file paths sorted by modification time."
            ),
            parameters={
                "type": "object",
                "properties": {
                    "pattern": {
                        "type": "string",
                        "description": 'Glob pattern to match (e.g. "**/*.py")',
                    },
                    "path": {
                        "type": "string",
                        "description": "Directory to search in. Default: current directory",
                    },
                },
                "required": ["pattern"],
            },
            permission=PermissionLevel.READ,
        )

    def execute(self, **kwargs: Any) -> str:
        pattern = kwargs["pattern"]
        search_dir = Path(kwargs.get("path", ".")).resolve()

        if not search_dir.is_dir():
            return f"Error: Directory not found: {search_dir}"

        try:
            matches = list(search_dir.glob(pattern))
        except ValueError as e:
            return f"Error: Invalid glob pattern: {e}"

        if not matches:
            return f"No files matching '{pattern}' in {search_dir}"

        # Sort by modification time (newest first), limit results
        matches.sort(key=lambda p: p.stat().st_mtime, reverse=True)

        max_results = 200
        truncated = len(matches) > max_results
        display = matches[:max_results]

        lines = [f"Found {len(matches)} file(s) matching '{pattern}':"]
        for p in display:
            try:
                rel = p.relative_to(search_dir)
            except ValueError:
                rel = p
            lines.append(str(rel))

        if truncated:
            lines.append(f"... and {len(matches) - max_results} more")

        return "\n".join(lines)
