#!/usr/bin/env python3
"""
Sync media files between database references and filesystem
This will fix the 404 errors by ensuring all referenced files exist
"""

import os
import sys
import django
from pathlib import Path
import shutil
from PIL import Image
import io

# Setup Django
sys.path.append('.')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import CustomUser

def create_placeholder_image(width=100, height=100):
    """Create a simple placeholder image"""
    try:
        from PIL import Image, ImageDraw, ImageFont
        
        # Create a simple placeholder
        img = Image.new('RGB', (width, height), color='lightgray')
        draw = ImageDraw.Draw(img)
        
        # Add text
        text = "No Image"
        try:
            # Try to use a font
            font = ImageFont.load_default()
            bbox = draw.textbbox((0, 0), text, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]
        except:
            # Fallback if font fails
            text_width, text_height = 50, 10
        
        x = (width - text_width) // 2
        y = (height - text_height) // 2
        draw.text((x, y), text, fill='black')
        
        return img
    except ImportError:
        # If PIL not available, return None
        return None

def create_placeholder_file(file_path):
    """Create a placeholder file based on extension"""
    file_path = Path(file_path)
    file_path.parent.mkdir(parents=True, exist_ok=True)
    
    extension = file_path.suffix.lower()
    
    if extension in ['.jpg', '.jpeg', '.png']:
        # Create placeholder image
        img = create_placeholder_image()
        if img:
            if extension == '.png':
                img.save(file_path, 'PNG')
            else:
                img.save(file_path, 'JPEG')
            return True
        else:
            # Fallback: create a minimal valid image file
            # 1x1 transparent PNG
            png_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\x9cc\xf8\x0f\x00\x00\x01\x00\x01\x00\x00\x00\x00IEND\xaeB`\x82'
            with open(file_path, 'wb') as f:
                f.write(png_data)
            return True
    
    elif extension == '.pdf':
        # Create minimal PDF
        pdf_content = b'%PDF-1.4\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>\nendobj\n4 0 obj\n<< /Length 44 >>\nstream\nBT\n/F1 12 Tf\n100 700 Td\n(Placeholder Document) Tj\nET\nendstream\nendobj\nxref\n0 5\n0000000000 65535 f \n0000000009 00000 n \n0000000058 00000 n \n0000000115 00000 n \n0000000207 00000 n \ntrailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n299\n%%EOF'
        with open(file_path, 'wb') as f:
            f.write(pdf_content)
        return True
    
    else:
        # Create empty text file
        with open(file_path, 'w') as f:
            f.write('Placeholder file')
        return True

def copy_from_ruralpoint(file_path):
    """Try to copy file from RuralPoint system"""
    rural_file = Path('RuralPoint/media') / file_path
    branch_file = Path('media') / file_path
    
    if rural_file.exists():
        # Ensure directory exists
        branch_file.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(rural_file, branch_file)
        return True
    return False

def sync_user_files():
    """Sync all user files"""
    print("🔄 Syncing media files for all users...")
    
    missing_files = []
    copied_files = []
    created_placeholders = []
    
    # Get all users
    users = CustomUser.objects.all()
    print(f"📊 Found {users.count()} users to check")
    
    for user in users:
        print(f"\n👤 Checking user: {user.username}")
        
        # List of file fields to check
        file_fields = [
            ('id_document', user.id_document),
            ('selfie', user.selfie),
            ('utility_bill', user.utility_bill),
            ('bank_statement', user.bank_statement),
            ('business_license', user.business_license),
            ('tax_certificate', user.tax_certificate),
            ('logbook', user.logbook),
            ('title_deed', user.title_deed),
            ('signature', user.signature),
        ]
        
        for field_name, file_field in file_fields:
            if file_field and str(file_field).strip():
                file_path = str(file_field)
                branch_file = Path('media') / file_path
                
                if not branch_file.exists():
                    print(f"  ❌ Missing: {file_path}")
                    missing_files.append((user.username, field_name, file_path))
                    
                    # Try to copy from RuralPoint first
                    if copy_from_ruralpoint(file_path):
                        print(f"  ✅ Copied from RuralPoint: {file_path}")
                        copied_files.append(file_path)
                    else:
                        # Create placeholder
                        if create_placeholder_file(branch_file):
                            print(f"  📄 Created placeholder: {file_path}")
                            created_placeholders.append(file_path)
                        else:
                            print(f"  ❌ Failed to create placeholder: {file_path}")
                else:
                    print(f"  ✅ Exists: {file_path}")
    
    print(f"\n📊 Summary:")
    print(f"Missing files found: {len(missing_files)}")
    print(f"Files copied from RuralPoint: {len(copied_files)}")
    print(f"Placeholder files created: {len(created_placeholders)}")
    
    return missing_files, copied_files, created_placeholders

def main():
    print("🚀 HAVEN GRAZURI INVESTMENT LIMITED- Media Files Sync")
    print("=" * 50)
    
    try:
        # Ensure media directories exist
        media_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',
        ]
        
        for dir_path in media_dirs:
            Path(dir_path).mkdir(parents=True, exist_ok=True)
        
        print("✅ Created media directory structure")
        
        # Sync files
        missing, copied, created = sync_user_files()
        
        print("\n🎉 Media sync completed!")
        print("Now all database references should have corresponding files.")
        print("The 404 errors should be resolved.")
        
    except Exception as e:
        print(f"❌ Error during sync: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    main()