import re
import os

# Services that need the fix
services_with_chrome = [
    'services/google-search/main.py',
    'services/bing-search/main.py',
    'services/duckduckgo-search/main.py'
]

for service_file in services_with_chrome:
    if os.path.exists(service_file):
        print(f"Fixing permissions in {service_file}")
        
        with open(service_file, 'r') as f:
            content = f.read()
        
        # Replace the ChromeDriverManager setup with a more robust version
        old_pattern = r'# Clear cache and get driver path\n        driver_path = ChromeDriverManager\(\)\.install\(\)\n        # Fix for WebDriver Manager cache issue\n        if driver_path\.endswith\(\'THIRD_PARTY_NOTICES\.chromedriver\'\):\n            import os\n            driver_dir = os\.path\.dirname\(driver_path\)\n            actual_driver = os\.path\.join\(driver_dir, \'chromedriver\'\)\n            if os\.path\.exists\(actual_driver\):\n                driver_path = actual_driver\n        service = ChromeService\(driver_path\)'
        
        new_pattern = '''# Clear cache and get driver path
        driver_path = ChromeDriverManager().install()
        # Fix for WebDriver Manager cache issue
        if driver_path.endswith('THIRD_PARTY_NOTICES.chromedriver'):
            import os
            driver_dir = os.path.dirname(driver_path)
            actual_driver = os.path.join(driver_dir, 'chromedriver')
            if os.path.exists(actual_driver):
                driver_path = actual_driver
        
        # Fix permissions
        import stat
        os.chmod(driver_path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
        service = ChromeService(driver_path)'''
        
        content = re.sub(old_pattern, new_pattern, content, flags=re.MULTILINE)
        
        with open(service_file, 'w') as f:
            f.write(content)
        
        print(f"Fixed {service_file}")

print("ChromeDriver permission fixes applied!")
