"""Write file tool - Write content to local files."""

from pathlib import Path
from typing import Any

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


class WriteFileTool(Tool):
    """Tool for writing to local files."""

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

    @property
    def description(self) -> str:
        return "Write content to a file at the specified path. Creates the file if it doesn't exist."

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "The path to the file to write",
                },
                "content": {
                    "type": "string",
                    "description": "The content to write to the file",
                },
                "encoding": {
                    "type": "string",
                    "description": "The file encoding (default: utf-8)",
                    "default": "utf-8",
                },
                "append": {
                    "type": "boolean",
                    "description": "Append to file instead of overwriting (default: false)",
                    "default": False,
                },
            },
            "required": ["path", "content"],
        }

    def execute(
        self,
        path: str,
        content: str,
        encoding: str = "utf-8",
        append: bool = False,
    ) -> ToolResult:
        """Write content to a file."""
        try:
            file_path = Path(path).expanduser().resolve()

            # Create parent directories if they don't exist
            file_path.parent.mkdir(parents=True, exist_ok=True)

            mode = "a" if append else "w"
            file_path.write_text(
                content if not append else content,
                encoding=encoding,
            )

            if append:
                with open(file_path, mode, encoding=encoding) as f:
                    f.write(content)
            else:
                file_path.write_text(content, encoding=encoding)

            action = "Appended to" if append else "Wrote to"
            return ToolResult.ok(f"{action} file: {path}")

        except PermissionError:
            return ToolResult.fail(f"Permission denied: {path}")
        except Exception as e:
            return ToolResult.fail(f"Error writing file: {e}")
