#!/usr/bin/env python3
"""
Fix image paths for existing users in the database
This script will update old image paths to match the current media structure
"""

import os
import sys
import django
from django.db import connection
import shutil
from pathlib import Path

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

def fix_user_image_paths():
    """Fix image paths for all users"""
    print("🖼️ Fixing user image paths...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Get all users with images
        users_with_images = User.objects.exclude(
            id_document__isnull=True
        ).exclude(id_document__exact='')
        
        print(f"📊 Found {users_with_images.count()} users with images")
        
        fixed_count = 0
        moved_count = 0
        
        for user in users_with_images:
            print(f"\n👤 Processing user: {user.email}")
            
            # Check all image fields
            image_fields = [
                ('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/'),
            ]
            
            user_updated = False
            
            for field_name, expected_prefix in image_fields:
                field_value = getattr(user, field_name)
                
                if field_value:
                    field_value_str = str(field_value)
                    print(f"  📄 {field_name}: {field_value_str}")
                    
                    # Check if the file exists at the current path
                    current_path = os.path.join('media', field_value_str)
                    
                    if os.path.exists(current_path):
                        print(f"    ✅ File exists at: {current_path}")
                        continue
                    
                    # Try to find the file in the media directory
                    filename = os.path.basename(field_value_str)
                    
                    # Search for the file in media directory
                    found_file = None
                    for root, dirs, files in os.walk('media'):
                        if filename in files:
                            found_file = os.path.join(root, filename)
                            break
                    
                    if found_file:
                        # Calculate the new path
                        new_path = expected_prefix + filename
                        new_full_path = os.path.join('media', new_path)
                        
                        # Create directory if it doesn't exist
                        os.makedirs(os.path.dirname(new_full_path), exist_ok=True)
                        
                        # Move the file to the correct location
                        try:
                            shutil.move(found_file, new_full_path)
                            print(f"    📁 Moved: {found_file} → {new_full_path}")
                            
                            # Update the database field
                            setattr(user, field_name, new_path)
                            user_updated = True
                            moved_count += 1
                            
                        except Exception as e:
                            print(f"    ❌ Error moving file: {e}")
                    else:
                        print(f"    ⚠️ File not found: {filename}")
            
            if user_updated:
                user.save()
                fixed_count += 1
                print(f"  ✅ Updated user: {user.email}")
        
        print(f"\n🎉 Summary:")
        print(f"  📊 Users processed: {users_with_images.count()}")
        print(f"  ✅ Users updated: {fixed_count}")
        print(f"  📁 Files moved: {moved_count}")
        
        return True
        
    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

def create_missing_directories():
    """Create missing media directories"""
    print("\n📁 Creating missing media directories...")
    
    directories = [
        "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",
        "media/documents",
        "media/receipts",
        "media/reports"
    ]
    
    for directory in directories:
        os.makedirs(directory, exist_ok=True)
        print(f"  ✅ {directory}")
    
    print("✅ All directories created")

def check_media_permissions():
    """Check and fix media directory permissions"""
    print("\n🔐 Checking media directory permissions...")
    
    try:
        media_dir = 'media'
        
        if os.path.exists(media_dir):
            # Try to create a test file
            test_file = os.path.join(media_dir, 'test_permissions.txt')
            try:
                with open(test_file, 'w') as f:
                    f.write('test')
                os.remove(test_file)
                print("  ✅ Media directory is writable")
            except Exception as e:
                print(f"  ⚠️ Media directory permission issue: {e}")
        else:
            print("  ❌ Media directory doesn't exist")
            
    except Exception as e:
        print(f"  ❌ Permission check error: {e}")

def list_media_files():
    """List all files in media directory for debugging"""
    print("\n📋 Listing media files...")
    
    try:
        media_dir = 'media'
        if not os.path.exists(media_dir):
            print("  ❌ Media directory doesn't exist")
            return
        
        file_count = 0
        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)
                print(f"  📄 {rel_path}")
                file_count += 1
        
        print(f"\n📊 Total files found: {file_count}")
        
    except Exception as e:
        print(f"❌ Error listing files: {e}")

if __name__ == "__main__":
    print("🚀 Starting image path fix...")
    print("=" * 60)
    
    # Create directories first
    create_missing_directories()
    
    # Check permissions
    check_media_permissions()
    
    # List current files (for debugging)
    list_media_files()
    
    # Fix user image paths
    success = fix_user_image_paths()
    
    if success:
        print("\n" + "=" * 60)
        print("🎉 IMAGE PATH FIX COMPLETED SUCCESSFULLY!")
        print("✅ All user image paths have been updated")
        print("✅ Files have been moved to correct locations")
        print("✅ Media directories are properly structured")
        print("\n🔄 Please test image loading in the application")
    else:
        print("\n" + "=" * 60)
        print("❌ IMAGE PATH FIX FAILED!")
        print("Please check the error messages above")
    
    sys.exit(0 if success else 1)