#!/usr/bin/env python3
"""
Simple Media Files Fix Script
Fixes missing media files by clearing invalid database references
"""

import os
import sys
import django
from pathlib import Path

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

from django.conf import settings
from users.models import CustomUser
from django.db import models

def check_and_fix_media():
    """Check for missing media files and clear invalid references"""
    print("🔍 Checking media files...")
    
    fixed_count = 0
    
    # Check selfie files
    users_with_selfies = CustomUser.objects.exclude(selfie='').exclude(selfie__isnull=True)
    for user in users_with_selfies:
        if user.selfie:
            file_path = os.path.join(settings.MEDIA_ROOT, user.selfie.name)
            if not os.path.exists(file_path):
                print(f"❌ Missing selfie for {user.get_full_name()}: {user.selfie.name}")
                user.selfie = None
                user.save()
                fixed_count += 1
    
    # Check ID front files
    users_with_id_front = CustomUser.objects.exclude(id_front='').exclude(id_front__isnull=True)
    for user in users_with_id_front:
        if user.id_front:
            file_path = os.path.join(settings.MEDIA_ROOT, user.id_front.name)
            if not os.path.exists(file_path):
                print(f"❌ Missing ID front for {user.get_full_name()}: {user.id_front.name}")
                user.id_front = None
                user.save()
                fixed_count += 1
    
    # Check ID back files
    users_with_id_back = CustomUser.objects.exclude(id_back='').exclude(id_back__isnull=True)
    for user in users_with_id_back:
        if user.id_back:
            file_path = os.path.join(settings.MEDIA_ROOT, user.id_back.name)
            if not os.path.exists(file_path):
                print(f"❌ Missing ID back for {user.get_full_name()}: {user.id_back.name}")
                user.id_back = None
                user.save()
                fixed_count += 1
    
    print(f"✅ Fixed {fixed_count} invalid media references")
    return fixed_count

def create_media_directories():
    """Create missing media directories"""
    print("📁 Creating media directories...")
    
    directories = [
        'kyc/id_documents',
        'kyc/selfies', 
        'kyc/bank_statements',
        'kyc/business_licenses',
        'kyc/signatures',
        'kyc/utility_bills',
        'kyc/tax_certificates',
        'kyc/title_deeds',
        'kyc/logbooks',
        'profile_images',
        'receipts'
    ]
    
    for directory in directories:
        full_path = os.path.join(settings.MEDIA_ROOT, directory)
        os.makedirs(full_path, exist_ok=True)
        print(f"✅ Created: {full_path}")

def main():
    print("🔧 HAVEN GRAZURI INVESTMENT LIMITED- Simple Media Fix")
    print("=" * 50)
    
    try:
        # Create directories
        create_media_directories()
        
        # Fix invalid references
        fixed_count = check_and_fix_media()
        
        print(f"\n📋 SUMMARY: Fixed {fixed_count} invalid media references")
        print("\n🎯 NEXT STEPS:")
        print("   1. Upload missing media files to production server")
        print("   2. Restart your Django application")
        print("   3. Test the client list page - images should no longer cause 404 errors")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()
        return 1
    
    return 0

if __name__ == "__main__":
    sys.exit(main())
