import os
import re
from openharness.tools.tool import Tool


class SearchTool(Tool):
    """Tool to search for patterns in files"""
    
    def __init__(self, base_dir=None):
        super().__init__("search")
        if base_dir is not None:
            self.base_dir = os.path.abspath(base_dir)
        else:
            self.base_dir = None
    
    def run(self, pattern: str, path: str = ".") -> str:
        """Search for pattern in files under the given path"""
        try:
            # Determine base directory
            if self.base_dir is not None:
                base = self.base_dir
            else:
                base = os.getcwd()
            
            # If path is ".", use base_dir, otherwise join with base
            if path == ".":
                search_root = base
            else:
                search_root = os.path.abspath(os.path.join(base, path))
            
            # Resolve to real paths for security check
            real_base = os.path.realpath(base)
            real_search_root = os.path.realpath(search_root)
            
            # Security: ensure the search root is within the base directory
            if not real_search_root.startswith(real_base + os.sep) and real_search_root != real_base:
                return f"Error: Access to path '{path}' is not allowed for security reasons"
            
            # Check if the search path exists
            if not os.path.exists(real_search_root):
                return f"Error: Path '{path}' is not accessible or does not exist"
            
            # Compile regex pattern
            regex = re.compile(pattern)
            
            results = []
            # Walk through directory
            for root, dirs, files in os.walk(real_search_root):
                # Skip hidden directories
                dirs[:] = [d for d in dirs if not d.startswith('.')]
                
                for file in files:
                    # Skip hidden files
                    if file.startswith('.'):
                        continue
                    
                    file_path = os.path.join(root, file)
                    try:
                        with open(file_path, 'r') as f:
                            for line_num, line in enumerate(f, 1):
                                if regex.search(line):
                                    results.append(f"{file_path}:{line_num}: {line.rstrip()}")
                    except (UnicodeDecodeError, PermissionError):
                        # Skip binary files or files we can't read
                        continue
            
            if results:
                return "\n".join(results)
            else:
                return f"No matches found for pattern '{pattern}' in '{path}'"
                
        except re.error as e:
            return f"Invalid regex pattern '{pattern}': {str(e)}"
        except Exception as e:
            return f"Error searching: {str(e)}"
    
    def get_description(self) -> str:
        return "Search for a pattern in files"
