import os
from openharness.tools.tool import Tool


class WriteFileTool(Tool):
    """Tool to write file contents"""

    def __init__(self, base_dir=None):
        super().__init__("write_file")
        if base_dir is not None:
            self.base_dir = os.path.abspath(base_dir)
        else:
            self.base_dir = None

    def run(self, path: str, content: str) -> str:
        """Write content to a file"""
        try:
            # Use base_dir if provided, otherwise use current working directory
            if self.base_dir is not None:
                base = self.base_dir
            else:
                base = os.getcwd()
            
            # Resolve the requested path to absolute and real path
            requested_path = os.path.abspath(os.path.join(base, path))
            real_base = os.path.realpath(base)
            real_requested = os.path.realpath(requested_path)
            
            # Security: ensure the real path is within the base directory
            if not real_requested.startswith(real_base + os.sep) and real_requested != real_base:
                return f"Error: Access to path '{path}' is not allowed for security reasons"

            # Create directory if it doesn't exist
            directory = os.path.dirname(real_requested)
            if directory and not os.path.exists(directory):
                os.makedirs(directory)

            with open(real_requested, "w") as f:
                f.write(content)

            return f"Successfully wrote to {path}"
        except Exception as e:
            return f"Error writing to file '{path}': {str(e)}"

    def get_description(self) -> str:
        return "Write content to a file"
