#!/usr/bin/env python3
"""
Fix image paths for existing users in production database
This script updates database records to have correct image paths
"""

import os
import sys
import django

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

def fix_production_image_paths():
    """Fix image paths in production database"""
    print("🔧 PRODUCTION: Fixing image paths in database...")
    
    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 field mappings - old patterns to new patterns
        image_field_fixes = [
            ('id_document', 'kyc/id_documents/'),
            ('selfie', 'kyc/selfies/'),
            ('utility_bill', 'kyc/utility_bills/'),
            ('bank_statement', 'kyc/bank_statements/'),
            ('business_license', 'kyc/business_licenses/'),
            ('tax_certificate', 'kyc/tax_certificates/'),
            ('logbook', 'kyc/logbooks/'),
            ('title_deed', 'kyc/title_deeds/'),
            ('signature', 'kyc/signatures/'),
            ('profile_image', 'profile_images/'),
        ]
        
        fixed_users = 0
        total_fixes = 0
        
        for user in users:
            user_updated = False
            user_fixes = []
            
            for field_name, correct_prefix in image_field_fixes:
                field_value = getattr(user, field_name)
                
                if field_value:
                    current_path = str(field_value)
                    
                    # Skip if already has correct prefix
                    if current_path.startswith(correct_prefix):
                        continue
                    
                    # Extract filename from current path
                    filename = os.path.basename(current_path)
                    
                    # Skip empty filenames
                    if not filename:
                        continue
                    
                    # Create correct path
                    correct_path = correct_prefix + filename
                    
                    # Update the field
                    setattr(user, field_name, correct_path)
                    user_updated = True
                    user_fixes.append(f"{field_name}: {current_path} → {correct_path}")
                    total_fixes += 1
            
            if user_updated:
                try:
                    user.save()
                    fixed_users += 1
                    print(f"✅ Fixed {user.email}:")
                    for fix in user_fixes:
                        print(f"   📄 {fix}")
                except Exception as e:
                    print(f"❌ Error saving {user.email}: {e}")
        
        print(f"\n🎉 PRODUCTION FIX SUMMARY:")
        print(f"   👥 Users checked: {users.count()}")
        print(f"   ✅ Users updated: {fixed_users}")
        print(f"   📄 Total path fixes: {total_fixes}")
        
        return True
        
    except Exception as e:
        print(f"❌ CRITICAL ERROR: {e}")
        return False

def verify_image_paths():
    """Verify that image paths are now correct"""
    print("\n🔍 Verifying image paths...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Check users with images
        users_with_images = User.objects.exclude(id_document__isnull=True).exclude(id_document__exact='')
        
        correct_paths = 0
        incorrect_paths = 0
        
        expected_prefixes = [
            'kyc/id_documents/',
            'kyc/selfies/',
            'kyc/utility_bills/',
            'kyc/bank_statements/',
            'kyc/business_licenses/',
            'kyc/tax_certificates/',
            'kyc/logbooks/',
            'kyc/title_deeds/',
            'kyc/signatures/',
            'profile_images/',
        ]
        
        for user in users_with_images:
            image_fields = ['id_document', 'selfie', 'utility_bill', 'bank_statement', 
                          'business_license', 'tax_certificate', 'logbook', 'title_deed', 
                          'signature', 'profile_image']
            
            for field_name in image_fields:
                field_value = getattr(user, field_name)
                
                if field_value:
                    path = str(field_value)
                    
                    # Check if path starts with any expected prefix
                    has_correct_prefix = any(path.startswith(prefix) for prefix in expected_prefixes)
                    
                    if has_correct_prefix:
                        correct_paths += 1
                    else:
                        incorrect_paths += 1
                        print(f"⚠️ Incorrect path: {user.email} - {field_name}: {path}")
        
        print(f"📊 Path verification results:")
        print(f"   ✅ Correct paths: {correct_paths}")
        print(f"   ❌ Incorrect paths: {incorrect_paths}")
        print(f"   📈 Success rate: {(correct_paths/(correct_paths+incorrect_paths)*100):.1f}%" if (correct_paths+incorrect_paths) > 0 else "   📈 Success rate: N/A")
        
        return incorrect_paths == 0
        
    except Exception as e:
        print(f"❌ Verification error: {e}")
        return False

def test_sample_urls():
    """Test some sample image URLs"""
    print("\n🧪 Testing sample image URLs...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Get a few users with images
        users_with_images = User.objects.exclude(id_document__isnull=True).exclude(id_document__exact='')[:3]
        
        for user in users_with_images:
            print(f"\n👤 Testing URLs for: {user.email}")
            
            image_fields = ['id_document', 'selfie', 'utility_bill', 'bank_statement', 'profile_image']
            
            for field_name in image_fields:
                field_value = getattr(user, field_name)
                
                if field_value:
                    path = str(field_value)
                    url = f"https://branchbusinessadvance.co.ke/media/{path}"
                    print(f"   📄 {field_name}: {url}")
        
        print("\n💡 Test these URLs in your browser to verify they work!")
        
        return True
        
    except Exception as e:
        print(f"❌ URL test error: {e}")
        return False

if __name__ == "__main__":
    print("🚀 PRODUCTION IMAGE PATH FIX STARTING...")
    print("=" * 70)
    
    # Fix the paths
    success = fix_production_image_paths()
    
    if success:
        # Verify the fixes
        verification_success = verify_image_paths()
        
        # Test sample URLs
        test_sample_urls()
        
        print("\n" + "=" * 70)
        if verification_success:
            print("🎉 PRODUCTION IMAGE PATH FIX COMPLETED SUCCESSFULLY!")
            print("✅ All image paths have been corrected in the database")
            print("✅ Images should now load properly in the application")
            print("\n🔄 No application restart required - changes are immediate")
        else:
            print("⚠️ PRODUCTION IMAGE PATH FIX COMPLETED WITH WARNINGS!")
            print("Some paths may still need manual correction")
    else:
        print("\n" + "=" * 70)
        print("❌ PRODUCTION IMAGE PATH FIX FAILED!")
        print("Please check the error messages above")
    
    print("\n📝 Next steps:")
    print("1. Test image loading in the application")
    print("2. Check that old user images now display correctly")
    print("3. Verify new user images still work properly")
    
    sys.exit(0 if success else 1)