#!/usr/bin/env python3
import os
import re

# Path to the settings file
settings_file = "/var/www/html/bloggers_ems/bloggers_ems/settings.py"

# The domain we're adding
new_domain = "bloggersmeetups.org"

# Read the current settings file
with open(settings_file, 'r') as f:
    content = f.read()

# Find the ALLOWED_HOSTS line
allowed_hosts_pattern = r"ALLOWED_HOSTS\s*=\s*\[([^\]]+)\]"
match = re.search(allowed_hosts_pattern, content)

if match:
    # Get the current hosts
    hosts_str = match.group(1)
    # Parse the hosts - handle both comma and space separated lists
    hosts = [h.strip().strip("'").strip('"') for h in re.split(r'[,\s]+', hosts_str) if h.strip()]
    # Remove duplicates and empty strings
    unique_hosts = list(set([h for h in hosts if h]))
    
    # Make sure the new domain is included
    if new_domain not in unique_hosts:
        unique_hosts.append(new_domain)
    if f"www.{new_domain}" not in unique_hosts:
        unique_hosts.append(f"www.{new_domain}")
    
    # Format the new ALLOWED_HOSTS line
    new_hosts_str = "ALLOWED_HOSTS = [" + ", ".join([f"'{h}'" for h in unique_hosts]) + "]"
    
    # Replace the old line with the new one
    new_content = re.sub(allowed_hosts_pattern, new_hosts_str, content)
    
    # Write the updated content back to the file
    with open(settings_file, 'w') as f:
        f.write(new_content)
    
    print(f"Updated ALLOWED_HOSTS in settings.py: {new_hosts_str}")
else:
    print("Could not find ALLOWED_HOSTS in settings.py")

# Now check and fix the .env file if it exists
env_file = "/var/www/html/bloggers_ems/.env"
if os.path.exists(env_file):
    with open(env_file, 'r') as f:
        env_content = f.read()
    
    # Find ALLOWED_HOSTS in .env
    env_pattern = r"ALLOWED_HOSTS\s*=\s*['\"]([^'\"]+)['\"]" 
    env_match = re.search(env_pattern, env_content)
    
    if env_match:
        # Get current hosts from .env
        env_hosts_str = env_match.group(1)
        env_hosts = [h.strip() for h in env_hosts_str.split(',') if h.strip()]
        
        # Remove duplicates
        unique_env_hosts = list(set(env_hosts))
        
        # Add new domain if not present
        if new_domain not in unique_env_hosts:
            unique_env_hosts.append(new_domain)
        if f"www.{new_domain}" not in unique_env_hosts:
            unique_env_hosts.append(f"www.{new_domain}")
        
        # Create new .env line
        new_env_hosts = ','.join(unique_env_hosts)
        new_env_line = f"ALLOWED_HOSTS ='{new_env_hosts}'"
        
        # Replace in .env file
        new_env_content = re.sub(env_pattern, new_env_line, env_content)
        
        with open(env_file, 'w') as f:
            f.write(new_env_content)
        
        print(f"Updated ALLOWED_HOSTS in .env: {new_env_line}")
    else:
        print("Could not find ALLOWED_HOSTS in .env")
else:
    print(".env file not found")
