#!/usr/bin/env python
import os
import re
import shutil
from pathlib import Path

def print_header(message):
    print(f"\n{'=' * 60}")
    print(f" {message}")
    print(f"{'=' * 60}\n")

def print_step(message):
    print(f"🔧 {message}")

def print_success(message):
    print(f"✅ {message}")

def print_warning(message):
    print(f"⚠️ {message}")

def print_error(message):
    print(f"❌ {message}")

def backup_file(file_path):
    """Create a backup of the specified file"""
    if os.path.exists(file_path):
        backup_dir = os.path.join(os.path.dirname(os.path.dirname(file_path)), 'backups')
        os.makedirs(backup_dir, exist_ok=True)
        
        backup_path = os.path.join(backup_dir, os.path.basename(file_path) + '.bak')
        shutil.copy2(file_path, backup_path)
        print_success(f"Backed up {file_path} to {backup_path}")
        return True
    else:
        print_warning(f"File not found: {file_path}")
        return False

def update_settings_production():
    """Update settings_production.py for proper static file handling"""
    print_step("Updating settings_production.py...")
    
    # Get the base directory
    base_dir = os.path.dirname(os.path.abspath(__file__))
    settings_path = os.path.join(base_dir, 'branch_system', 'settings_production.py')
    
    if os.path.exists(settings_path):
        # Backup the file
        backup_file(settings_path)
        
        with open(settings_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Check if DEBUG is set to False
        debug_pattern = re.compile(r'DEBUG\s*=\s*(True|False)')
        match = debug_pattern.search(content)
        if match:
            if match.group(1) == 'True':
                content = content.replace('DEBUG = True', 'DEBUG = False')
                print_success("Set DEBUG = False")
        else:
            # If DEBUG is not found, add it
            content += "\n\n# Disable debug mode for production\nDEBUG = False\n"
            print_success("Added DEBUG = False")
        
        # Ensure STATIC_URL is properly set
        if 'STATIC_URL' not in content:
            content += "\n# URL prefix for static files\nSTATIC_URL = '/static/'\n"
            print_success("Added STATIC_URL = '/static/'")
        
        # Ensure STATIC_ROOT is set to 'staticfiles'
        static_root_pattern = re.compile(r'STATIC_ROOT\s*=\s*.*')
        match = static_root_pattern.search(content)
        if match:
            if "'staticfiles'" not in match.group(0) and '"staticfiles"' not in match.group(0):
                content = content.replace(match.group(0), "STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')")
                print_success("Updated STATIC_ROOT to use 'staticfiles' directory")
        else:
            content += "\n# Absolute path to the directory where collectstatic will collect static files\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\n"
            print_success("Added STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')")
        
        # Ensure STATICFILES_DIRS is properly configured
        if 'STATICFILES_DIRS' not in content:
            content += "\n# Additional locations of static files\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]\n"
            print_success("Added STATICFILES_DIRS configuration")
        
        # Ensure MEDIA_URL is properly set
        if 'MEDIA_URL' not in content:
            content += "\n# URL that handles the media served from MEDIA_ROOT\nMEDIA_URL = '/media/'\n"
            print_success("Added MEDIA_URL = '/media/'")
        
        # Ensure MEDIA_ROOT is properly set
        if 'MEDIA_ROOT' not in content:
            content += "\n# Absolute filesystem path to the directory that will hold user-uploaded files\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n"
            print_success("Added MEDIA_ROOT = os.path.join(BASE_DIR, 'media')")
        
        # Add STATICFILES_FINDERS if not present
        if 'STATICFILES_FINDERS' not in content:
            content += "\n# Finders for static files\nSTATICFILES_FINDERS = [\n    'django.contrib.staticfiles.finders.FileSystemFinder',\n    'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n]\n"
            print_success("Added STATICFILES_FINDERS configuration")
        
        # Write updated content
        with open(settings_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print_success("Updated settings_production.py")
    else:
        print_error(f"settings_production.py not found at {settings_path}")

def update_urls_py():
    """Update urls.py to ensure proper static/media file handling"""
    print_step("Updating urls.py...")
    
    # Get the base directory
    base_dir = os.path.dirname(os.path.abspath(__file__))
    urls_path = os.path.join(base_dir, 'branch_system', 'urls.py')
    
    if os.path.exists(urls_path):
        # Backup the file
        backup_file(urls_path)
        
        with open(urls_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Check if static/media patterns are already included
        if 'static(' not in content or 'media(' not in content:
            # Find the imports section
            import_section = re.search(r'from django\.contrib import admin.*?\n', content)
            if import_section:
                # Add static and media imports if not present
                if 'from django.conf import settings' not in content:
                    new_imports = "from django.conf import settings\n"
                    content = content[:import_section.end()] + new_imports + content[import_section.end():]
                
                if 'from django.conf.urls.static import static' not in content:
                    new_imports = "from django.conf.urls.static import static\n"
                    content = content[:import_section.end()] + new_imports + content[import_section.end():]
            
            # Find the urlpatterns section
            urlpatterns_end = content.find(']', content.find('urlpatterns'))
            if urlpatterns_end != -1:
                # Add static and media patterns
                new_patterns = "\n\n# Always serve media files through Django\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n"
                new_patterns += "# Serve static files through Django in debug mode, otherwise through web server\nif settings.DEBUG:\n    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n"
                
                content = content[:urlpatterns_end+1] + new_patterns + content[urlpatterns_end+1:]
                print_success("Added static and media URL patterns")
        
        # Write updated content
        with open(urls_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print_success("Updated urls.py")
    else:
        print_error(f"urls.py not found at {urls_path}")

def main():
    print_header("HAVEN GRAZURI INVESTMENT LIMITED- Settings Production Update")
    
    # Update settings_production.py
    update_settings_production()
    
    # Update urls.py
    update_urls_py()
    
    print_header("UPDATE COMPLETED")
    print("""\n📋 Next Steps:
1. Run the fix_static_production.py script
2. Run the verify_static_fix.py script
3. Restart your web server
4. Test the website with DEBUG=False
5. Verify that client names are displaying correctly
6. Verify that images are loading properly\n""")

if __name__ == "__main__":
    main()