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

# Set up Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.conf import settings

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(settings.BASE_DIR, '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 fix_htaccess():
    """Enhance .htaccess file for better static file handling"""
    print_step("Updating .htaccess file...")
    
    htaccess_path = os.path.join(settings.BASE_DIR, '.htaccess')
    if os.path.exists(htaccess_path):
        # Backup the file
        backup_file(htaccess_path)
        
        with open(htaccess_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Create an enhanced .htaccess file with improved static file handling
        new_htaccess = """\
# Django .htaccess file for cPanel - Enhanced for Static Files
# This file configures Apache to work with your Django application

# Enable rewrite engine
RewriteEngine On

# Serve static files from staticfiles directory with fallback to static
RewriteCond %{REQUEST_URI} ^/static/(.*)$
RewriteCond %{DOCUMENT_ROOT}/staticfiles/%1 -f
RewriteRule ^static/(.*)$ staticfiles/$1 [L]

# Fallback to static directory if file not found in staticfiles
RewriteCond %{REQUEST_URI} ^/static/(.*)$
RewriteCond %{DOCUMENT_ROOT}/static/%1 -f
RewriteRule ^static/(.*)$ static/$1 [L]

# Serve media files
RewriteCond %{REQUEST_URI} ^/media/(.*)$
RewriteRule ^media/(.*)$ media/$1 [L]

# Additional fallback for static files - try both directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/static/(.*)$
RewriteCond %{DOCUMENT_ROOT}/staticfiles/%1 -f
RewriteRule ^static/(.*)$ staticfiles/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/static/(.*)$
RewriteCond %{DOCUMENT_ROOT}/static/%1 -f
RewriteRule ^static/(.*)$ static/$1 [L]

# Security headers
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options nosniff
    Header always set X-XSS-Protection "1; mode=block"
    Header always set X-Frame-Options SAMEORIGIN
    Header always set Referrer-Policy strict-origin-when-cross-origin
</IfModule>

# Enable compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

# Enable caching for static files
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
</IfModule>

# Redirect all other requests to Django
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /passenger_wsgi.py/$1 [QSA,L]
"""
        
        # Write the new content
        with open(htaccess_path, 'w', encoding='utf-8') as f:
            f.write(new_htaccess)
        
        print_success("Updated .htaccess file with enhanced static file handling")
    else:
        print_warning(f".htaccess not found at {htaccess_path}")

def fix_settings_production():
    """Update settings_production.py for proper static file handling"""
    print_step("Updating settings_production.py...")
    
    settings_path = os.path.join(settings.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()
        
        # Ensure STATICFILES_DIRS is properly configured
        if 'STATICFILES_DIRS' not in content:
            # Find STATIC_ROOT line
            static_root_pattern = re.compile(r'STATIC_ROOT\s*=\s*.*')
            match = static_root_pattern.search(content)
            if match:
                # Add STATICFILES_DIRS after STATIC_ROOT
                insert_pos = match.end()
                staticfiles_dirs = "\n\n# Additional locations of static files\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]\n"
                content = content[:insert_pos] + staticfiles_dirs + content[insert_pos:]
                print_success("Added STATICFILES_DIRS configuration")
        
        # Ensure STATIC_ROOT is set to 'staticfiles'
        if "STATIC_ROOT = os.path.join(BASE_DIR, 'static')" in content:
            content = content.replace("STATIC_ROOT = os.path.join(BASE_DIR, 'static')", "STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')")
            print_success("Updated STATIC_ROOT to use 'staticfiles' directory")
        
        # Write updated content
        with open(settings_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print_success("Updated settings_production.py")
    else:
        print_warning(f"settings_production.py not found at {settings_path}")

def collect_static():
    """Run collectstatic to ensure all static files are in the staticfiles directory"""
    print_step("Collecting static files...")
    
    try:
        from django.core.management import call_command
        call_command('collectstatic', interactive=False, verbosity=0)
        print_success("Static files collected successfully")
    except Exception as e:
        print_error(f"Error collecting static files: {e}")

def set_file_permissions():
    """Set proper file permissions for static and media files"""
    print_step("Setting proper file permissions...")
    
    try:
        # Set permissions for static files
        static_dir = Path(settings.BASE_DIR) / 'static'
        staticfiles_dir = Path(settings.STATIC_ROOT)
        media_dir = Path(settings.MEDIA_ROOT)
        
        for directory in [static_dir, staticfiles_dir, media_dir]:
            if directory.exists():
                for root, dirs, files in os.walk(directory):
                    for d in dirs:
                        os.chmod(os.path.join(root, d), 0o755)
                    for f in files:
                        os.chmod(os.path.join(root, f), 0o644)
                print_success(f"Set permissions for {directory}")
            else:
                print_warning(f"Directory not found: {directory}")
    except Exception as e:
        print_error(f"Error setting file permissions: {e}")

def main():
    print_header("HAVEN GRAZURI INVESTMENT LIMITED- Static Files Production Fix")
    
    # Backup critical files
    backup_file(os.path.join(settings.BASE_DIR, 'branch_system', 'settings_production.py'))
    backup_file(os.path.join(settings.BASE_DIR, '.htaccess'))
    
    # Fix .htaccess file
    fix_htaccess()
    
    # Fix settings_production.py
    fix_settings_production()
    
    # Collect static files
    collect_static()
    
    # Set file permissions
    set_file_permissions()
    
    print_header("FIX COMPLETED")
    print("""\n📋 Next Steps:
1. Restart your web server
2. Test the website with DEBUG=False
3. Verify that client names are displaying correctly
4. Verify that images are loading properly\n""")

if __name__ == "__main__":
    main()