#!/usr/bin/env python3
"""
Check current image paths in the database and file system
"""

import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
django.setup()

def check_image_paths():
    """Check all user image paths"""
    print("🔍 Checking user image paths...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Get all users
        users = User.objects.all()
        
        print(f"📊 Checking {users.count()} users...")
        
        image_fields = [
            'id_document',
            'selfie', 
            'utility_bill',
            'bank_statement',
            'business_license',
            'tax_certificate',
            'logbook',
            'title_deed',
            'signature',
            'profile_image'
        ]
        
        total_images = 0
        existing_images = 0
        missing_images = 0
        
        for user in users:
            user_has_images = False
            
            for field_name in image_fields:
                field_value = getattr(user, field_name)
                
                if field_value:
                    total_images += 1
                    user_has_images = True
                    
                    # Convert FieldFile to string
                    field_value_str = str(field_value)
                    
                    # Check if file exists
                    file_path = os.path.join('media', field_value_str)
                    
                    if os.path.exists(file_path):
                        existing_images += 1
                        status = "✅"
                    else:
                        missing_images += 1
                        status = "❌"
                    
                    if not user_has_images:
                        print(f"\n👤 {user.email}:")
                        user_has_images = True
                    
                    print(f"  {status} {field_name}: {field_value_str}")
        
        print(f"\n📊 Summary:")
        print(f"  Total images in database: {total_images}")
        print(f"  ✅ Existing files: {existing_images}")
        print(f"  ❌ Missing files: {missing_images}")
        print(f"  📈 Success rate: {(existing_images/total_images*100):.1f}%" if total_images > 0 else "  📈 Success rate: N/A")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

def check_media_structure():
    """Check media directory structure"""
    print("\n📁 Checking media directory structure...")
    
    expected_dirs = [
        "media/kyc/id_documents",
        "media/kyc/selfies",
        "media/kyc/utility_bills", 
        "media/kyc/bank_statements",
        "media/kyc/business_licenses",
        "media/kyc/tax_certificates",
        "media/kyc/logbooks",
        "media/kyc/title_deeds",
        "media/kyc/signatures",
        "media/profile_images"
    ]
    
    for directory in expected_dirs:
        if os.path.exists(directory):
            file_count = len([f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))])
            print(f"  ✅ {directory} ({file_count} files)")
        else:
            print(f"  ❌ {directory} (missing)")

def find_orphaned_files():
    """Find files in media directory that aren't referenced in database"""
    print("\n🔍 Finding orphaned files...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Get all image paths from database
        db_paths = set()
        
        image_fields = [
            'id_document', 'selfie', 'utility_bill', 'bank_statement',
            'business_license', 'tax_certificate', 'logbook', 'title_deed',
            'signature', 'profile_image'
        ]
        
        for user in User.objects.all():
            for field_name in image_fields:
                field_value = getattr(user, field_name)
                if field_value:
                    db_paths.add(str(field_value))
        
        # Get all files in media directory
        media_files = set()
        media_dir = 'media'
        
        if os.path.exists(media_dir):
            for root, dirs, files in os.walk(media_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    rel_path = os.path.relpath(file_path, media_dir)
                    media_files.add(rel_path)
        
        # Find orphaned files
        orphaned = media_files - db_paths
        
        print(f"📊 File analysis:")
        print(f"  Database references: {len(db_paths)}")
        print(f"  Media files: {len(media_files)}")
        print(f"  Orphaned files: {len(orphaned)}")
        
        if orphaned:
            print(f"\n🗑️ Orphaned files:")
            for file in sorted(orphaned):
                print(f"  📄 {file}")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

if __name__ == "__main__":
    print("🚀 Starting image path analysis...")
    print("=" * 60)
    
    check_image_paths()
    check_media_structure()
    find_orphaned_files()
    
    print("\n" + "=" * 60)
    print("🎉 Analysis completed!")
    print("\nNext steps:")
    print("1. Run fix_image_paths.py to fix missing files")
    print("2. Check media directory permissions")
    print("3. Test image loading in the application")