import re

# Read the original docker-compose.yml
with open('docker-compose.yml', 'r') as f:
    content = f.read()

# List of services that need Redis URL
services_needing_redis = [
    'google-search-service',
    'bing-search-service',
    'yandex-search-service',
    'duckduckgo-search-service',
    'yahoo-search-service',
    'baidu-search-service',
    'metadata-service',
    'file-export-service'
]

# Add REDIS_URL to each service
for service in services_needing_redis:
    # Find the service section and add REDIS_URL
    pattern = rf'({service}:.*?)environment:(.*?)(\n      - LOG_LEVEL=INFO)'
    
    def replace_func(match):
        service_part = match.group(1)
        env_part = match.group(2)
        log_level_part = match.group(3)
        
        # Add REDIS_URL before LOG_LEVEL
        if 'REDIS_URL' not in env_part:
            return f'{service_part}environment:{env_part}\n      - REDIS_URL=redis://redis:6379{log_level_part}'
        else:
            return match.group(0)
    
    content = re.sub(pattern, replace_func, content, flags=re.DOTALL)

# Add Redis dependency to services that need it
for service in services_needing_redis:
    # Find the service section and add redis dependency
    pattern = rf'({service}:.*?)depends_on:\n      kafka:\n        condition: service_healthy'
    
    def replace_func(match):
        service_part = match.group(1)
        return f'{service_part}depends_on:\n      kafka:\n        condition: service_healthy\n      redis:\n        condition: service_healthy'
    
    content = re.sub(pattern, replace_func, content, flags=re.DOTALL)

# Write the updated content
with open('docker-compose.yml', 'w') as f:
    f.write(content)

print("Docker Compose file updated successfully!")
