#!/usr/bin/env python3
"""
Script to encrypt passwords in .env file
"""

import os
import sys
import re

# Add the backend directory to the Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.utils.encryption import encrypt_password

def encrypt_env_passwords():
    """Encrypt all password fields in the .env file"""
    env_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
    
    if not os.path.exists(env_file_path):
        print(f"Error: .env file not found at {env_file_path}")
        return
    
    # Read the current .env file
    with open(env_file_path, 'r') as file:
        content = file.read()
    
    # Define password fields to encrypt
    password_fields = [
        'DATABASE_PASSWORD',
        'MAIL_PASSWORD', 
        'SUPPORT_PASSWORD',
        'EVALUATION_PASSWORD',
        'ADMIN_PASSWORD'
    ]
    
    # Encrypt each password field
    for field in password_fields:
        pattern = f'^{field}=(.*)$'
        match = re.search(pattern, content, re.MULTILINE)
        
        if match:
            current_value = match.group(1).strip()
            
            # Skip if already encrypted (check if it's a very long base64-like string)
            if len(current_value) > 50 and '!' not in current_value and '@' not in current_value:
                print(f"Skipping {field} - appears to be already encrypted")
                continue
            
            # Encrypt the password
            encrypted_value = encrypt_password(current_value)
            
            # Replace in content
            content = re.sub(pattern, f'{field}={encrypted_value}', content, flags=re.MULTILINE)
            print(f"Encrypted {field}: {current_value[:10]}... -> {encrypted_value[:20]}...")
    
    # Write the updated content back to .env
    with open(env_file_path, 'w') as file:
        file.write(content)
    
    print(f"\n✅ Encryption completed! Updated .env file at {env_file_path}")
    print("⚠️  Make sure to update your configuration loader to decrypt these values!")

if __name__ == "__main__":
    encrypt_env_passwords()