import os
from openharness.tools.tool import Tool


class ReadFileTool(Tool):
    """Tool to read file contents"""

    def __init__(self, base_dir=None):
        super().__init__("read_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) -> str:
        """Read and return the contents of 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
            # Use os.path.commonpath or check that real path starts with real base + separator
            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"

            with open(real_requested, "r") as f:
                return f.read()
        except FileNotFoundError:
            return f"Error: File '{path}' not found"
        except Exception as e:
            return f"Error reading file '{path}': {str(e)}"

    def get_description(self) -> str:
        return "Read the contents of a file"
