#!/usr/bin/env python

import os
import sys
import shutil
import stat
from pathlib import Path

# Add the project directory to the Python path
sys.path.insert(0, os.path.dirname(__file__))

# Set production settings
os.environ["DJANGO_SETTINGS_MODULE"] = "branch_system.settings_production"

# Import Django modules after setting the environment
import django
django.setup()

from django.conf import settings
from django.core.management import call_command

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 fix_static_files():
    print_step("Fixing static files configuration...")
    
    # Ensure static directories exist
    static_root = Path(settings.STATIC_ROOT)
    static_dir = Path(settings.BASE_DIR) / 'static'
    
    if not static_root.exists():
        print_step(f"Creating static root directory: {static_root}")
        static_root.mkdir(parents=True, exist_ok=True)
    
    if not static_dir.exists():
        print_step(f"Creating static directory: {static_dir}")
        static_dir.mkdir(parents=True, exist_ok=True)
    
    # Collect static files
    print_step("Collecting static files...")
    try:
        call_command('collectstatic', interactive=False, verbosity=0)
        print_success("Static files collected successfully")
    except Exception as e:
        print_warning(f"Error collecting static files: {e}")
        print_step("Trying manual copy of static files...")
        
        # Manual copy of static files
        if static_dir.exists() and static_root.exists():
            for item in static_dir.glob('**/*'):
                if item.is_file():
                    rel_path = item.relative_to(static_dir)
                    dest_path = static_root / rel_path
                    dest_path.parent.mkdir(parents=True, exist_ok=True)
                    shutil.copy2(item, dest_path)
            print_success("Manual copy of static files completed")
    
    # Set proper permissions
    print_step("Setting proper permissions for static files...")
    try:
        for root, dirs, files in os.walk(static_root):
            for dir_name in dirs:
                os.chmod(os.path.join(root, dir_name), 0o755)
            for file_name in files:
                os.chmod(os.path.join(root, file_name), 0o644)
        print_success("Static file permissions set")
    except Exception as e:
        print_warning(f"Could not set static file permissions: {e}")

def fix_media_files():
    print_step("Fixing media files configuration...")
    
    # Ensure media directory exists
    media_root = Path(settings.MEDIA_ROOT)
    if not media_root.exists():
        print_step(f"Creating media directory: {media_root}")
        media_root.mkdir(parents=True, exist_ok=True)
    
    # Create common media subdirectories
    subdirs = [
        'kyc', 'kyc/bank_statements', 'kyc/business_licenses', 'kyc/id_documents',
        'kyc/logbooks', 'kyc/selfies', 'kyc/signatures', 'kyc/tax_certificates',
        'kyc/title_deeds', 'kyc/utility_bills', 'profile_images', 'receipts'
    ]
    
    for subdir in subdirs:
        subdir_path = media_root / subdir
        if not subdir_path.exists():
            subdir_path.mkdir(parents=True, exist_ok=True)
            print_step(f"Created: {subdir_path}")
    
    # Set proper permissions
    print_step("Setting proper permissions for media files...")
    try:
        os.chmod(media_root, 0o755)
        for root, dirs, files in os.walk(media_root):
            for dir_name in dirs:
                os.chmod(os.path.join(root, dir_name), 0o755)
            for file_name in files:
                os.chmod(os.path.join(root, file_name), 0o644)
        print_success("Media file permissions set")
    except Exception as e:
        print_warning(f"Could not set media file permissions: {e}")

def update_htaccess():
    print_step("Updating .htaccess file...")
    
    htaccess_content = """# Django .htaccess file for cPanel - Optimized for Static Files
# This file configures Apache to work with your Django application

# Enable rewrite engine
RewriteEngine On

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

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

# Handle media files - serve directly if file exists
RewriteCond %{REQUEST_URI} ^/media/
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^media/(.*)$ media/$1 [L]

# Handle media files - fallback to Django if file doesn't exist
RewriteCond %{REQUEST_URI} ^/media/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^media/(.*)$ /passenger_wsgi.py/media/$1 [QSA,L]

# Redirect all other requests to Django
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /passenger_wsgi.py/$1 [QSA,L]

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

# Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

# Cache static files
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/ico "access plus 1 month"
    ExpiresByType image/icon "access plus 1 month"
    ExpiresByType text/plain "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
</IfModule>
"""
    
    htaccess_path = Path(settings.BASE_DIR) / '.htaccess'
    with open(htaccess_path, 'w') as f:
        f.write(htaccess_content)
    
    print_success("Updated .htaccess file")

def update_settings_production():
    print_step("Updating settings_production.py...")
    
    settings_path = Path(settings.BASE_DIR) / 'branch_system' / 'settings_production.py'
    
    with open(settings_path, 'r') as f:
        content = f.read()
    
    # Make sure STATICFILES_DIRS is properly configured
    if 'STATICFILES_DIRS' not in content:
        # Find the static and media files section
        static_section = "# Static and Media Files\nSTATIC_ROOT = "
        static_section_pos = content.find(static_section)
        
        if static_section_pos != -1:
            # Find the end of the section
            next_section_pos = content.find('\n\n', static_section_pos)
            if next_section_pos != -1:
                # Insert STATICFILES_DIRS
                staticfiles_dirs = "\n\n# Ensure Django serves static files in production\nSTATICFILES_DIRS = [\n    os.path.join(BASE_DIR, 'static'),\n]"
                updated_content = content[:next_section_pos] + staticfiles_dirs + content[next_section_pos:]
                
                with open(settings_path, 'w') as f:
                    f.write(updated_content)
                
                print_success("Added STATICFILES_DIRS to settings_production.py")
    
    # Update WSGI configuration
    wsgi_path = Path(settings.BASE_DIR) / 'branch_system' / 'wsgi.py'
    with open(wsgi_path, 'r') as f:
        wsgi_content = f.read()
    
    if "'branch_system.settings'" in wsgi_content:
        updated_wsgi = wsgi_content.replace("'branch_system.settings'", "'branch_system.settings_production'")
        with open(wsgi_path, 'w') as f:
            f.write(updated_wsgi)
        print_success("Updated wsgi.py to use production settings")

def update_urls_py():
    print_step("Updating urls.py...")
    
    urls_path = Path(settings.BASE_DIR) / 'branch_system' / 'urls.py'
    with open(urls_path, 'r') as f:
        content = f.read()
    
    # Check if we need to update the static/media serving
    if "urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)" in content:
        # Find the static/media serving section
        static_section = "# Serve media files"
        static_section_pos = content.find(static_section)
        
        if static_section_pos != -1:
            # Find the end of the section
            next_section_pos = content.find('\n\n', static_section_pos)
            if next_section_pos != -1:
                # Replace with conditional serving
                new_static_section = """# Serve media files (both development and production)
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
else:
    # In production, static files should be served by the web server
    # But we still need to serve media files through Django
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)"""
                
                # Find the start of the actual static serving lines
                static_lines_pos = content.find("urlpatterns += static", static_section_pos)
                if static_lines_pos != -1 and static_lines_pos < next_section_pos:
                    # Replace just the static serving lines
                    end_static_lines = content.find('\n\n', static_lines_pos)
                    if end_static_lines == -1 or end_static_lines > next_section_pos:
                        end_static_lines = next_section_pos
                    
                    updated_content = content[:static_section_pos] + "# Serve media files (both development and production)\n" + new_static_section + content[end_static_lines:]
                    
                    with open(urls_path, 'w') as f:
                        f.write(updated_content)
                    
                    print_success("Updated urls.py for proper static/media file serving")

def fix_overlapping_client_names():
    print_step("Checking for CSS issues with client names...")
    
    # Look for CSS files that might control client name display
    css_files = []
    for root, dirs, files in os.walk(Path(settings.BASE_DIR) / 'static' / 'css'):
        for file in files:
            if file.endswith('.css'):
                css_files.append(os.path.join(root, file))
    
    # Check templates for client name display
    templates_dir = Path(settings.BASE_DIR) / 'templates'
    client_templates = []
    if templates_dir.exists():
        for root, dirs, files in os.walk(templates_dir):
            for file in files:
                if file.endswith('.html'):
                    with open(os.path.join(root, file), 'r', encoding='utf-8', errors='ignore') as f:
                        content = f.read()
                        if 'client' in content.lower() and ('name' in content.lower() or 'list' in content.lower()):
                            client_templates.append(os.path.join(root, file))
    
    # Create or update CSS fix
    css_fix_path = Path(settings.BASE_DIR) / 'static' / 'css' / 'table-fix.css'
    css_fix_content = """/* Fix for overlapping client names */
.client-name {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
}

/* Fix for table layouts */
.table-responsive {
    overflow-x: auto;
}

.table td, .table th {
    white-space: nowrap;
    padding: 8px;
}

/* Fix for client list display */
.client-list-item {
    margin-bottom: 10px;
    padding: 10px;
    border-bottom: 1px solid #eee;
}

/* Ensure images display properly */
img {
    max-width: 100%;
    height: auto;
}

/* Fix for profile images */
.profile-image {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 50%;
}

/* Fix for document thumbnails */
.document-thumbnail {
    width: 150px;
    height: 150px;
    object-fit: contain;
}
"""
    
    with open(css_fix_path, 'w') as f:
        f.write(css_fix_content)
    
    print_success("Created/updated CSS fixes for client names and images")
    
    # Create JS fix for tables
    js_fix_path = Path(settings.BASE_DIR) / 'static' / 'js' / 'table-fix.js'
    js_fix_content = """// Fix for table display and client names
document.addEventListener('DOMContentLoaded', function() {
    // Add client-name class to client name elements
    const clientNameElements = document.querySelectorAll('.client-name, td:contains("client"), td:contains("name")');
    clientNameElements.forEach(function(element) {
        if (!element.classList.contains('client-name')) {
            element.classList.add('client-name');
        }
    });
    
    // Make tables responsive
    const tables = document.querySelectorAll('table');
    tables.forEach(function(table) {
        if (!table.parentElement.classList.contains('table-responsive')) {
            const wrapper = document.createElement('div');
            wrapper.classList.add('table-responsive');
            table.parentNode.insertBefore(wrapper, table);
            wrapper.appendChild(table);
        }
        if (!table.classList.contains('table')) {
            table.classList.add('table');
        }
    });
    
    // Fix image display
    const images = document.querySelectorAll('img');
    images.forEach(function(img) {
        // Ensure image has alt text
        if (!img.hasAttribute('alt')) {
            img.setAttribute('alt', 'Image');
        }
        
        // Add loading="lazy" for better performance
        if (!img.hasAttribute('loading')) {
            img.setAttribute('loading', 'lazy');
        }
    });
});
"""
    
    with open(js_fix_path, 'w') as f:
        f.write(js_fix_content)
    
    print_success("Created/updated JS fixes for tables and client names")

def main():
    print_header("HAVEN GRAZURI INVESTMENT LIMITED- Media & Static Files Fix")
    
    # Fix static files
    fix_static_files()
    
    # Fix media files
    fix_media_files()
    
    # Update .htaccess
    update_htaccess()
    
    # Update settings_production.py
    update_settings_production()
    
    # Update urls.py
    update_urls_py()
    
    # Fix overlapping client names
    fix_overlapping_client_names()
    
    # Collect static files again to ensure all fixes are applied
    print_step("Final static files collection...")
    try:
        call_command('collectstatic', interactive=False, verbosity=0)
        print_success("Static files collected successfully")
    except Exception as e:
        print_warning(f"Error collecting static files: {e}")
    
    print_header("FIX COMPLETED")
    print("\n📋 Next Steps:")
    print("1. Restart your web server")
    print("2. Test the website to ensure images are loading")
    print("3. Verify client names are displaying correctly")
    print("\n🔍 If issues persist:")
    print("- Check server error logs")
    print("- Verify file permissions (755 for directories, 644 for files)")
    print("- Ensure .htaccess is being read by Apache")
    print("- Consider temporarily setting DEBUG=True to diagnose issues")

if __name__ == "__main__":
    main()