import re

def update_env_file(filepath):
    try:
        with open(filepath, 'r') as f:
            content = f.read()
            
        # Remove old variables
        content = re.sub(r'(?m)^EMAIL_PROVIDER=.*$', '', content)
        content = re.sub(r'(?m)^SMTP_HOST=.*$', '', content)
        content = re.sub(r'(?m)^SMTP_PORT=.*$', '', content)
        content = re.sub(r'(?m)^SMTP_USER=.*$', '', content)
        content = re.sub(r'(?m)^SMTP_PASSWORD=.*$', '', content)
        content = re.sub(r'(?m)^MAIL_FROM=.*$', '', content)
        content = re.sub(r'(?m)^MAIL_FROM_NAME=.*$', '', content)
        content = re.sub(r'(?m)^EMAILS_FROM_EMAIL=.*$', '', content)
        content = re.sub(r'(?m)^SENDGRID_API_KEY=.*$', '', content)
        
        # Squeeze blank lines that might have been created
        content = re.sub(r'\n{3,}', '\n\n', content)
        
        new_vars = """
EMAIL_PROVIDER=smtp
SMTP_HOST=mail.servicefinder.hu
SMTP_PORT=465
SMTP_USER=noreply@servicefinder.hu
SMTP_PASSWORD=Mailsender99!
MAIL_FROM=noreply@servicefinder.hu
MAIL_FROM_NAME=ServiceFinder
"""
        with open(filepath, 'w') as f:
            f.write(content.strip() + "\n" + new_vars)
            
        print(f"Updated {filepath}")
    except FileNotFoundError:
        print(f"File not found: {filepath}")

update_env_file('.env')
update_env_file('backend/.env')
