import re
import sys

def replace_in_file(filepath):
    with open(filepath, 'r') as f:
        text = f.read()

    # Protect specific strings
    text = text.replace('api/public-demo/agents', '__API_PUBLIC_DEMO_AGENTS__')
    text = text.replace("'agent'", '__Q_AGENT__')
    text = text.replace('"agent"', '__DQ_AGENT__')
    text = text.replace('role: \'agent\'', '__ROLE_AGENT__')
    text = text.replace('speaker === \'agent\'', '__SPEAKER_AGENT__')

    # Global replacements
    # Using regex for word boundaries
    text = re.sub(r'\bAgents\b', 'Workers', text)
    text = re.sub(r'\bagents\b', 'workers', text)
    text = re.sub(r'\bAgent\b', 'Worker', text)
    text = re.sub(r'\bagent\b', 'worker', text)
    
    text = re.sub(r'\bAGENTS\b', 'WORKERS', text)
    text = re.sub(r'\bAGENT\b', 'WORKER', text)

    # Restore protected strings
    text = text.replace('__API_PUBLIC_DEMO_AGENTS__', 'api/public-demo/agents')
    text = text.replace('__Q_AGENT__', "'agent'")
    text = text.replace('__DQ_AGENT__', '"agent"')
    text = text.replace('__ROLE_AGENT__', "role: 'agent'")
    text = text.replace('__SPEAKER_AGENT__', "speaker === 'agent'")

    with open(filepath, 'w') as f:
        f.write(text)

files = [
    'resources/views/home.blade.php',
    'resources/views/layouts/app.blade.php',
    'routes/api.php'
]

for file in files:
    try:
        replace_in_file(file)
        print(f"Replaced in {file}")
    except Exception as e:
        print(f"Failed {file}: {e}")
