"""Write tool — writes content to files."""

from __future__ import annotations

import os
from typing import Any

from pi_agents.agent.types import AgentTool, AgentToolResult
from pi_agents.ai.types import TextContent


WRITE_TOOL_NAME = "write"
WRITE_TOOL_DESCRIPTION = "Write content to a file. Creates parent directories if needed."

WRITE_TOOL_PARAMETERS = {
    "type": "object",
    "properties": {
        "path": {"type": "string", "description": "File path to write"},
        "content": {"type": "string", "description": "Content to write"},
    },
    "required": ["path", "content"],
}


def create_write_tool(cwd: str | None = None) -> AgentTool:
    """Create a write tool for writing files."""

    class WriteTool(AgentTool):
        def __init__(self) -> None:
            super().__init__(
                name=WRITE_TOOL_NAME,
                description=WRITE_TOOL_DESCRIPTION,
                parameters=WRITE_TOOL_PARAMETERS,
            )
            self.label = "Write"

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

            if cwd and not os.path.isabs(path):
                path = os.path.join(cwd, path)

            try:
                os.makedirs(os.path.dirname(path), exist_ok=True)
                with open(path, "w", encoding="utf-8") as f:
                    f.write(content)
                byte_count = len(content.encode("utf-8"))
                return AgentToolResult(
                    content=[TextContent(type="text", text=f"Wrote {byte_count} bytes to {path}")]
                )
            except Exception as e:
                return AgentToolResult(
                    content=[TextContent(type="text", text=f"Error writing file: {e}")]
                )

    return WriteTool()
