"""Read a file from the workspace.

Returns the contents of a file as text.
"""

from pathlib import Path

from core.pathways.models.tool import ToolOutput


async def run(
    path: str,
    encoding: str = "utf-8",
) -> ToolOutput:
    """
    Args:
        path: Path to the file to read
        encoding: File encoding (default: utf-8).
    """
    if not path:
        return ToolOutput(success=False, error="path is required")

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

        if not file_path.exists():
            return ToolOutput(success=False, error=f"File not found: {path}")

        if not file_path.is_file():
            return ToolOutput(success=False, error=f"Not a file: {path}")

        content = file_path.read_text(encoding=encoding)

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

    except UnicodeDecodeError:
        return ToolOutput(
            success=False,
            error=f"Cannot decode file with encoding {encoding}",
        )
    except PermissionError:
        return ToolOutput(success=False, error=f"Permission denied: {path}")
    except Exception as e:
        return ToolOutput(success=False, error=str(e))
