"""Write file tool — create or overwrite a file."""

from __future__ import annotations

from pathlib import Path
from typing import Any

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


class WriteFileTool(BaseTool):
    """Create or overwrite a file with given content."""

    def spec(self) -> ToolSpec:
        return ToolSpec(
            name="write_file",
            description=(
                "Write content to a file. Creates the file (and parent directories) "
                "if it doesn't exist. Overwrites if it does."
            ),
            parameters={
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "Path to the file to write",
                    },
                    "content": {
                        "type": "string",
                        "description": "Content to write to the file",
                    },
                },
                "required": ["file_path", "content"],
            },
            permission=PermissionLevel.WRITE,
        )

    def execute(self, **kwargs: Any) -> str:
        file_path = kwargs["file_path"]
        content = kwargs["content"]

        path = Path(file_path).resolve()

        try:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(content, encoding="utf-8")
            lines = content.count("\n") + (1 if content and not content.endswith("\n") else 0)
            return f"Successfully wrote {len(content)} bytes ({lines} lines) to {path}"
        except OSError as e:
            return f"Error writing file: {e}"
