"""Write content to a file in the workspace.

Creates or overwrites a file with the given content.
"""

from pathlib import Path

from core.pathways.models.tool import ToolOutput


async def run(
    path: str,
    content: str,
    create_dirs: bool = True,
    encoding: str = "utf-8",
) -> ToolOutput:
    """
    Args:
        path: Path to the file to write
        content: Content to write to the file
        create_dirs: Create parent directories if they don't exist
        encoding: File encoding (default: utf-8).
    """
    if not path:
        return ToolOutput(success=False, error="path is required")

    if content is None:
        return ToolOutput(success=False, error="content is required")

    try:
        file_path = Path(path).expanduser().resolve()

        if create_dirs:
            file_path.parent.mkdir(parents=True, exist_ok=True)

        file_path.write_text(content, encoding=encoding)

        return ToolOutput(
            success=True,
            data={"path": str(file_path), "size": len(content)},
        )

    except PermissionError:
        return ToolOutput(success=False, error=f"Permission denied: {path}")
    except Exception as e:
        return ToolOutput(success=False, error=str(e))
