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

# 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_check(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 verify_django_settings():
    """Verify Django settings for static file handling"""
    print_check("Checking Django settings...")
    
    # Check DEBUG setting
    debug_status = "enabled" if settings.DEBUG else "disabled"
    print(f"DEBUG is {debug_status}")
    
    # Check STATIC_ROOT
    if hasattr(settings, 'STATIC_ROOT'):
        print_success(f"STATIC_ROOT is set to: {settings.STATIC_ROOT}")
        static_root_path = Path(settings.STATIC_ROOT)
        if static_root_path.exists():
            print_success(f"STATIC_ROOT directory exists")
        else:
            print_warning(f"STATIC_ROOT directory does not exist: {static_root_path}")
    else:
        print_error("STATIC_ROOT is not defined")
    
    # Check STATICFILES_DIRS
    if hasattr(settings, 'STATICFILES_DIRS'):
        print_success(f"STATICFILES_DIRS is set to: {settings.STATICFILES_DIRS}")
        for static_dir in settings.STATICFILES_DIRS:
            static_dir_path = Path(static_dir)
            if static_dir_path.exists():
                print_success(f"Static directory exists: {static_dir_path}")
            else:
                print_warning(f"Static directory does not exist: {static_dir_path}")
    else:
        print_error("STATICFILES_DIRS is not defined")
    
    # Check STATIC_URL
    if hasattr(settings, 'STATIC_URL'):
        print_success(f"STATIC_URL is set to: {settings.STATIC_URL}")
    else:
        print_error("STATIC_URL is not defined")
    
    # Check MEDIA_ROOT
    if hasattr(settings, 'MEDIA_ROOT'):
        print_success(f"MEDIA_ROOT is set to: {settings.MEDIA_ROOT}")
        media_root_path = Path(settings.MEDIA_ROOT)
        if media_root_path.exists():
            print_success(f"MEDIA_ROOT directory exists")
        else:
            print_warning(f"MEDIA_ROOT directory does not exist: {media_root_path}")
    else:
        print_error("MEDIA_ROOT is not defined")
    
    # Check MEDIA_URL
    if hasattr(settings, 'MEDIA_URL'):
        print_success(f"MEDIA_URL is set to: {settings.MEDIA_URL}")
    else:
        print_error("MEDIA_URL is not defined")

def verify_file_structure():
    """Verify file structure for static files"""
    print_check("Checking file structure...")
    
    # Check if table-fix.css and table-fix.js exist in static directory
    static_css_path = Path(settings.BASE_DIR) / 'static' / 'css' / 'table-fix.css'
    static_js_path = Path(settings.BASE_DIR) / 'static' / 'js' / 'table-fix.js'
    
    if static_css_path.exists():
        print_success(f"table-fix.css exists in static directory")
    else:
        print_warning(f"table-fix.css not found in static directory: {static_css_path}")
    
    if static_js_path.exists():
        print_success(f"table-fix.js exists in static directory")
    else:
        print_warning(f"table-fix.js not found in static directory: {static_js_path}")
    
    # Check if table-fix.css and table-fix.js exist in staticfiles directory
    if hasattr(settings, 'STATIC_ROOT'):
        staticfiles_css_path = Path(settings.STATIC_ROOT) / 'css' / 'table-fix.css'
        staticfiles_js_path = Path(settings.STATIC_ROOT) / 'js' / 'table-fix.js'
        
        if staticfiles_css_path.exists():
            print_success(f"table-fix.css exists in staticfiles directory")
        else:
            print_warning(f"table-fix.css not found in staticfiles directory: {staticfiles_css_path}")
        
        if staticfiles_js_path.exists():
            print_success(f"table-fix.js exists in staticfiles directory")
        else:
            print_warning(f"table-fix.js not found in staticfiles directory: {staticfiles_js_path}")

def verify_htaccess():
    """Verify .htaccess configuration"""
    print_check("Checking .htaccess configuration...")
    
    htaccess_path = Path(settings.BASE_DIR) / '.htaccess'
    if htaccess_path.exists():
        with open(htaccess_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Check for static file handling rules
        if 'RewriteCond %{REQUEST_URI} ^/static/(.*)$' in content:
            print_success("Static file handling rules found in .htaccess")
        else:
            print_warning("Static file handling rules not found in .htaccess")
        
        # Check for media file handling rules
        if 'RewriteCond %{REQUEST_URI} ^/media/(.*)$' in content:
            print_success("Media file handling rules found in .htaccess")
        else:
            print_warning("Media file handling rules not found in .htaccess")
        
        # Check for compression
        if 'AddOutputFilterByType DEFLATE' in content:
            print_success("Compression is enabled in .htaccess")
        else:
            print_warning("Compression is not enabled in .htaccess")
        
        # Check for caching
        if 'ExpiresActive On' in content:
            print_success("Caching is enabled in .htaccess")
        else:
            print_warning("Caching is not enabled in .htaccess")
    else:
        print_error(f".htaccess file not found: {htaccess_path}")

def verify_template_inclusions():
    """Verify that table-fix.css and table-fix.js are included in base.html"""
    print_check("Checking template inclusions...")
    
    # Find base.html
    base_html_path = None
    for root, dirs, files in os.walk(settings.BASE_DIR):
        if 'base.html' in files:
            base_html_path = os.path.join(root, 'base.html')
            break
    
    if base_html_path:
        with open(base_html_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Check for table-fix.css inclusion
        css_included = re.search(r'<link[^>]*href=["\'](?:[^"\']*/)?css/table-fix\.css["\']', content) is not None
        if css_included:
            print_success("table-fix.css is included in base.html")
        else:
            print_warning("table-fix.css is not included in base.html")
            # Add table-fix.css if not included
            if '</head>' in content:
                new_content = content.replace('</head>', '    <link rel="stylesheet" href="{{ STATIC_URL }}css/table-fix.css">\n</head>')
                with open(base_html_path, 'w', encoding='utf-8') as f:
                    f.write(new_content)
                print_success("Added table-fix.css to base.html")
        
        # Check for table-fix.js inclusion
        js_included = re.search(r'<script[^>]*src=["\'](?:[^"\']*/)?js/table-fix\.js["\']', content) is not None
        if js_included:
            print_success("table-fix.js is included in base.html")
        else:
            print_warning("table-fix.js is not included in base.html")
            # Add table-fix.js if not included
            if '</body>' in content:
                new_content = content.replace('</body>', '    <script src="{{ STATIC_URL }}js/table-fix.js"></script>\n</body>')
                with open(base_html_path, 'w', encoding='utf-8') as f:
                    f.write(new_content)
                print_success("Added table-fix.js to base.html")
    else:
        print_error("base.html not found")

def create_fix_files_if_missing():
    """Create table-fix.css and table-fix.js if they don't exist"""
    print_check("Creating fix files if missing...")
    
    # Create static/css and static/js directories if they don't exist
    static_css_dir = Path(settings.BASE_DIR) / 'static' / 'css'
    static_js_dir = Path(settings.BASE_DIR) / 'static' / 'js'
    
    static_css_dir.mkdir(parents=True, exist_ok=True)
    static_js_dir.mkdir(parents=True, exist_ok=True)
    
    # Create table-fix.css if it doesn't exist
    css_path = static_css_dir / 'table-fix.css'
    if not css_path.exists():
        css_content = """\
/* Table fix styles */
.client-name {
    max-width: 150px;
    word-break: break-word;
}

.profile-image {
    max-width: 100%;
    height: auto;
    display: block;
}

.table-responsive {
    overflow-x: auto;
}

table td {
    padding: 8px;
    vertical-align: middle;
}
"""
        with open(css_path, 'w', encoding='utf-8') as f:
            f.write(css_content)
        print_success(f"Created {css_path}")
    
    # Create table-fix.js if it doesn't exist
    js_path = static_js_dir / 'table-fix.js'
    if not js_path.exists():
        js_content = """\
// Table fix script
document.addEventListener('DOMContentLoaded', function() {
    // Apply client-name class to table cells containing client names
    const clientNameCells = document.querySelectorAll('td:nth-child(2)');
    clientNameCells.forEach(cell => {
        cell.classList.add('client-name');
    });
    
    // Ensure tables have responsive wrapper
    const tables = document.querySelectorAll('table');
    tables.forEach(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);
        }
    });
});
"""
        with open(js_path, 'w', encoding='utf-8') as f:
            f.write(js_content)
        print_success(f"Created {js_path}")

def main():
    print_header("HAVEN GRAZURI INVESTMENT LIMITED- Static Files Verification")
    
    # Verify Django settings
    verify_django_settings()
    
    # Create fix files if missing
    create_fix_files_if_missing()
    
    # Verify file structure
    verify_file_structure()
    
    # Verify .htaccess configuration
    verify_htaccess()
    
    # Verify template inclusions
    verify_template_inclusions()
    
    print_header("VERIFICATION COMPLETED")
    print("""\n📋 Next Steps:
1. Run the fix_static_production.py script if issues were found
2. Restart your web server
3. Test the website with DEBUG=False
4. Verify that client names are displaying correctly
5. Verify that images are loading properly\n""")

if __name__ == "__main__":
    main()