#!/usr/bin/env python3
"""
Fix Media Files Script
This script addresses missing media files in production by:
1. Identifying database records with missing media files
2. Creating placeholder images for missing files
3. Updating database references to valid files
4. Syncing media files to production
"""

import os
import sys
import django
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
import shutil

# 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.core.files.storage import default_storage
from django.core.files.base import ContentFile
import io

def create_placeholder_image(text="No Image", size=(400, 300)):
    """Create a placeholder image with text"""
    img = Image.new('RGB', size, color='#f0f0f0')
    draw = ImageDraw.Draw(img)
    
    # Try to use a font, fallback to default if not available
    try:
        font = ImageFont.truetype("arial.ttf", 24)
    except:
        font = ImageFont.load_default()
    
    # Calculate text position to center it
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    
    x = (size[0] - text_width) // 2
    y = (size[1] - text_height) // 2
    
    draw.text((x, y), text, fill='#666666', font=font)
    
    # Save to bytes
    img_bytes = io.BytesIO()
    img.save(img_bytes, format='JPEG', quality=85)
    img_bytes.seek(0)
    
    return img_bytes

def check_media_files():
    """Check for missing media files and fix them"""
    print("🔍 Checking media files...")
    
    missing_files = []
    fixed_files = []
    
    # Check user profile images (selfies)
    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):
                missing_files.append({
                    'user': user,
                    'field': 'selfie',
                    'path': user.selfie.name,
                    'full_path': file_path
                })
    
    # Check ID documents
    users_with_id_front = CustomUser.objects.exclude(id_front='').exclude(id_front__isnull=True)
    users_with_id_back = CustomUser.objects.exclude(id_back='').exclude(id_back__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):
                missing_files.append({
                    'user': user,
                    'field': 'id_front',
                    'path': user.id_front.name,
                    'full_path': file_path
                })
    
    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):
                missing_files.append({
                    'user': user,
                    'field': 'id_back',
                    'path': user.id_back.name,
                    'full_path': file_path
                })
    
    print(f"📊 Found {len(missing_files)} missing media files")
    
    # Fix missing files
    for missing in missing_files:
        try:
            # Create directory if it doesn't exist
            os.makedirs(os.path.dirname(missing['full_path']), exist_ok=True)
            
            # Create placeholder image
            if missing['field'] == 'selfie':
                placeholder_text = f"{missing['user'].first_name}\nProfile Photo"
                img_bytes = create_placeholder_image(placeholder_text, (300, 300))
            elif missing['field'] in ['id_front', 'id_back']:
                placeholder_text = f"ID Document\n{missing['field'].replace('_', ' ').title()}"
                img_bytes = create_placeholder_image(placeholder_text, (400, 250))
            else:
                img_bytes = create_placeholder_image("Document", (400, 300))
            
            # Save placeholder image
            with open(missing['full_path'], 'wb') as f:
                f.write(img_bytes.getvalue())
            
            fixed_files.append(missing['path'])
            print(f"✅ Created placeholder for: {missing['path']}")
            
        except Exception as e:
            print(f"❌ Failed to create placeholder for {missing['path']}: {e}")
    
    return missing_files, fixed_files

def clean_invalid_references():
    """Clean up database references to files that don't exist"""
    print("🧹 Cleaning invalid media references...")
    
    cleaned_count = 0
    
    # Check and clean selfie references
    users = CustomUser.objects.exclude(selfie='').exclude(selfie__isnull=True)
    for user in users:
        if user.selfie and not default_storage.exists(user.selfie.name):
            print(f"🗑️  Clearing invalid selfie reference for user {user.get_full_name()}: {user.selfie.name}")
            user.selfie = None
            user.save()
            cleaned_count += 1
    
    # Check and clean ID document references
    users = CustomUser.objects.filter(
        models.Q(id_front__isnull=False) | models.Q(id_back__isnull=False)
    ).exclude(id_front='').exclude(id_back='')
    
    for user in users:
        if user.id_front and not default_storage.exists(user.id_front.name):
            print(f"🗑️  Clearing invalid ID front reference for user {user.get_full_name()}: {user.id_front.name}")
            user.id_front = None
            user.save()
            cleaned_count += 1
            
        if user.id_back and not default_storage.exists(user.id_back.name):
            print(f"🗑️  Clearing invalid ID back reference for user {user.get_full_name()}: {user.id_back.name}")
            user.id_back = None
            user.save()
            cleaned_count += 1
    
    print(f"✅ Cleaned {cleaned_count} invalid references")
    return cleaned_count

def sync_media_to_production():
    """Create a script to sync media files to production"""
    sync_script = """#!/bin/bash
# Media Files Sync Script for Production

echo "🚀 Starting media files sync to production..."

# Create media directories if they don't exist
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/id_documents
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/selfies
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/bank_statements
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/business_licenses
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/signatures
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/utility_bills
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/tax_certificates
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/title_deeds
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/logbooks
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/profile_images
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/receipts

# Set proper permissions
chmod -R 755 /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/

echo "✅ Media directories created and permissions set"

# Copy media files (you'll need to upload your local media files)
# rsync -avz ./media/ /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/

echo "📁 Media sync completed!"
"""
    
    with open('sync_media_production.sh', 'w') as f:
        f.write(sync_script)
    
    os.chmod('sync_media_production.sh', 0o755)
    print("📝 Created sync_media_production.sh script")

def main():
    print("🔧 HAVEN GRAZURI INVESTMENT LIMITED- Media Files Fix")
    print("=" * 50)
    
    try:
        # Check and fix missing files
        missing_files, fixed_files = check_media_files()
        
        # Clean invalid references
        cleaned_count = clean_invalid_references()
        
        # Create sync script
        sync_media_to_production()
        
        print("\n📋 SUMMARY:")
        print(f"   • Missing files found: {len(missing_files)}")
        print(f"   • Placeholder files created: {len(fixed_files)}")
        print(f"   • Invalid references cleaned: {cleaned_count}")
        print(f"   • Sync script created: sync_media_production.sh")
        
        if missing_files:
            print("\n📄 Missing files that were fixed:")
            for missing in missing_files:
                print(f"   - {missing['path']}")
        
        print("\n🎯 NEXT STEPS:")
        print("   1. Run: python manage.py collectstatic --noinput")
        print("   2. Upload your media files to production server")
        print("   3. Run the sync_media_production.sh script on production")
        print("   4. Test image display on the website")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        return 1
    
    return 0

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