"""Write file tool."""


TOOL_VERSION = "2026-05-22"

from __future__ import annotations

from pathlib import Path
from typing import Callable

from harzoo.agent.kernel.tool import Tool, ToolResult


def resolve_tool_path(path: str) -> Path:
    p = Path(path).expanduser()
    if p.is_absolute():
        return p.resolve()
    return (Path.cwd() / p).resolve()


def safe_file_op(fn: Callable) -> Callable:
    def wrapper(self, file_path: str, *args, **kwargs):
        try:
            return fn(self, file_path, *args, **kwargs)
        except FileNotFoundError:
            return ToolResult.failure(f"File not found: {file_path}", code="FILE_NOT_FOUND")
        except PermissionError as e:
            return ToolResult.failure(str(e), code="PERMISSION_DENIED")
        except Exception as e:
            return ToolResult.failure(str(e), code="TOOL_EXCEPTION")

    return wrapper


class WriteTool(Tool):
    name = "Write"
    description = "Write content to a file. Creates parent directories if needed."
    parameters = {
        "properties": {
            "file_path": {"type": "string", "description": "Path to the file"},
            "content": {"type": "string", "description": "Full file content"},
        },
        "required": ["file_path", "content"],
    }

    @safe_file_op
    def execute(self, file_path: str, content: str, **kwargs) -> ToolResult:
        p = resolve_tool_path(file_path)
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(content, encoding="utf-8")
        return ToolResult.success({"file_path": str(p), "chars_written": len(content)})


TOOL = WriteTool
