"""Read file tool - Read contents of local files."""

from pathlib import Path
from typing import Any

from agenai.agent.tools.base import Tool, ToolResult


class ReadFileTool(Tool):
    """Tool for reading local files."""

    @property
    def name(self) -> str:
        return "read_file"

    @property
    def description(self) -> str:
        return "Read the contents of a file at the specified path."

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "The path to the file to read",
                },
                "encoding": {
                    "type": "string",
                    "description": "The file encoding (default: utf-8)",
                    "default": "utf-8",
                },
            },
            "required": ["path"],
        }

    def execute(self, path: str, encoding: str = "utf-8") -> ToolResult:
        """Read a file and return its contents."""
        try:
            file_path = Path(path).expanduser().resolve()

            if not file_path.exists():
                return ToolResult.fail(f"File not found: {path}")

            if not file_path.is_file():
                return ToolResult.fail(f"Path is not a file: {path}")

            # Limit file size to prevent memory issues
            max_size = 1024 * 1024  # 1MB
            if file_path.stat().st_size > max_size:
                return ToolResult.fail(f"File too large (max {max_size // 1024}KB): {path}")

            content = file_path.read_text(encoding=encoding)
            return ToolResult.ok(content)

        except PermissionError:
            return ToolResult.fail(f"Permission denied: {path}")
        except UnicodeDecodeError:
            return ToolResult.fail(f"Cannot decode file with encoding {encoding}: {path}")
        except Exception as e:
            return ToolResult.fail(f"Error reading file: {e}")
