#!/usr/bin/env python

import os
import sys
import requests
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
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.files.storage import default_storage

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

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

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

def print_info(message):
    print(f"ℹ️ {message}")

def test_static_files():
    print_header("Testing Static Files Configuration")
    
    # Check if STATIC_ROOT exists
    static_root = Path(settings.STATIC_ROOT)
    if static_root.exists():
        print_success(f"STATIC_ROOT directory exists: {static_root}")
        
        # Count files in STATIC_ROOT
        file_count = sum(1 for _ in static_root.glob('**/*') if _.is_file())
        print_info(f"Found {file_count} files in STATIC_ROOT")
        
        if file_count == 0:
            print_error("No static files found in STATIC_ROOT. Static files collection may have failed.")
    else:
        print_error(f"STATIC_ROOT directory does not exist: {static_root}")
    
    # Check if STATICFILES_DIRS are configured
    if hasattr(settings, 'STATICFILES_DIRS'):
        print_success("STATICFILES_DIRS is configured")
        for static_dir in settings.STATICFILES_DIRS:
            static_path = Path(static_dir)
            if static_path.exists():
                print_success(f"Static directory exists: {static_path}")
                
                # Count files in static directory
                file_count = sum(1 for _ in static_path.glob('**/*') if _.is_file())
                print_info(f"Found {file_count} files in {static_path}")
            else:
                print_error(f"Static directory does not exist: {static_path}")
    else:
        print_error("STATICFILES_DIRS is not configured")
    
    # Check staticfiles storage
    print_info(f"Using staticfiles storage: {staticfiles_storage.__class__.__name__}")
    
    # Check if DEBUG is enabled
    if settings.DEBUG:
        print_info("DEBUG is enabled - Django will serve static files")
    else:
        print_info("DEBUG is disabled - Web server should serve static files")

def test_media_files():
    print_header("Testing Media Files Configuration")
    
    # Check if MEDIA_ROOT exists
    media_root = Path(settings.MEDIA_ROOT)
    if media_root.exists():
        print_success(f"MEDIA_ROOT directory exists: {media_root}")
        
        # Count files in MEDIA_ROOT
        file_count = sum(1 for _ in media_root.glob('**/*') if _.is_file())
        print_info(f"Found {file_count} files in MEDIA_ROOT")
    else:
        print_error(f"MEDIA_ROOT directory does not exist: {media_root}")
    
    # Check default storage
    print_info(f"Using default storage: {default_storage.__class__.__name__}")
    
    # Check media URL configuration
    print_info(f"MEDIA_URL is set to: {settings.MEDIA_URL}")

def test_htaccess():
    print_header("Testing .htaccess Configuration")
    
    htaccess_path = Path(settings.BASE_DIR) / '.htaccess'
    if htaccess_path.exists():
        print_success(f".htaccess file exists: {htaccess_path}")
        
        # Check for key directives in .htaccess
        with open(htaccess_path, 'r') as f:
            content = f.read()
            
        if 'RewriteEngine On' in content:
            print_success("RewriteEngine is enabled in .htaccess")
        else:
            print_error("RewriteEngine is not enabled in .htaccess")
            
        if 'RewriteRule ^static/(.*)$' in content:
            print_success("Static files rewrite rule found in .htaccess")
        else:
            print_error("Static files rewrite rule not found in .htaccess")
            
        if 'RewriteRule ^media/(.*)$' in content:
            print_success("Media files rewrite rule found in .htaccess")
        else:
            print_error("Media files rewrite rule not found in .htaccess")
    else:
        print_error(f".htaccess file does not exist: {htaccess_path}")

def test_urls_configuration():
    print_header("Testing URLs Configuration")
    
    urls_path = Path(settings.BASE_DIR) / 'branch_system' / 'urls.py'
    if urls_path.exists():
        print_success(f"urls.py file exists: {urls_path}")
        
        # Check for static/media serving in urls.py
        with open(urls_path, 'r') as f:
            content = f.read()
            
        if 'static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)' in content:
            print_success("Media URL pattern found in urls.py")
        else:
            print_error("Media URL pattern not found in urls.py")
            
        if settings.DEBUG:
            if 'static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)' in content:
                print_success("Static URL pattern found in urls.py (for DEBUG mode)")
            else:
                print_error("Static URL pattern not found in urls.py (needed for DEBUG mode)")
    else:
        print_error(f"urls.py file does not exist: {urls_path}")

def test_css_fixes():
    print_header("Testing CSS Fixes")
    
    css_fix_path = Path(settings.BASE_DIR) / 'static' / 'css' / 'table-fix.css'
    if css_fix_path.exists():
        print_success(f"CSS fix file exists: {css_fix_path}")
        
        # Check if CSS fix contains client name fixes
        with open(css_fix_path, 'r') as f:
            content = f.read()
            
        if '.client-name' in content:
            print_success("Client name CSS fix found")
        else:
            print_error("Client name CSS fix not found")
            
        if 'img {' in content:
            print_success("Image display CSS fix found")
        else:
            print_error("Image display CSS fix not found")
    else:
        print_error(f"CSS fix file does not exist: {css_fix_path}")
    
    # Check if CSS is included in static files
    css_fix_static_path = Path(settings.STATIC_ROOT) / 'css' / 'table-fix.css'
    if css_fix_static_path.exists():
        print_success(f"CSS fix file exists in static files: {css_fix_static_path}")
    else:
        print_error(f"CSS fix file does not exist in static files: {css_fix_static_path}")

def main():
    print_header("HAVEN GRAZURI INVESTMENT LIMITED- Media & Static Files Test")
    
    # Test static files configuration
    test_static_files()
    
    # Test media files configuration
    test_media_files()
    
    # Test .htaccess configuration
    test_htaccess()
    
    # Test URLs configuration
    test_urls_configuration()
    
    # Test CSS fixes
    test_css_fixes()
    
    print_header("TEST COMPLETED")
    print("\n📋 Summary:")
    print("If all tests passed, your static and media files should be properly configured.")
    print("If any tests failed, review the error messages and make the necessary corrections.")
    print("\n🔍 Remember:")
    print("- In production (DEBUG=False), static files should be served by the web server")
    print("- Media files should be served by Django regardless of DEBUG setting")
    print("- Client name display issues should be fixed by the CSS and JS fixes")

if __name__ == "__main__":
    main()