#!/usr/bin/env python3
"""
Check Media Files on Production Server
This script checks which media files exist in the database vs filesystem
"""

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

def check_media_files():
    """Check which media files exist in database vs filesystem"""
    print("🔍 Checking media files in database vs filesystem...")
    
    db_files = []
    missing_files = []
    existing_files = []
    
    # Get all users with media files
    users = CustomUser.objects.all()
    
    for user in users:
        # Check all document fields
        document_fields = [
            ('selfie', user.selfie),
            ('id_document', user.id_document),
            ('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),
            ('profile_image', user.profile_image),
        ]
        
        for field_name, field_value in document_fields:
            if field_value:
                db_files.append(field_value.name)
                file_path = os.path.join(settings.MEDIA_ROOT, field_value.name)
                if os.path.exists(file_path):
                    existing_files.append(field_value.name)
                else:
                    missing_files.append({
                        'user': user.get_full_name(),
                        'file': field_value.name,
                        'type': field_name
                    })
    
    print(f"\n📊 SUMMARY:")
    print(f"   • Total files in database: {len(db_files)}")
    print(f"   • Files existing on filesystem: {len(existing_files)}")
    print(f"   • Missing files: {len(missing_files)}")
    
    if missing_files:
        print(f"\n❌ MISSING FILES:")
        for missing in missing_files[:10]:  # Show first 10
            print(f"   • {missing['user']}: {missing['file']} ({missing['type']})")
        if len(missing_files) > 10:
            print(f"   ... and {len(missing_files) - 10} more")
    
    # Check what files exist in media directory
    media_root = Path(settings.MEDIA_ROOT)
    if media_root.exists():
        print(f"\n📁 MEDIA DIRECTORY STRUCTURE:")
        for root, dirs, files in os.walk(media_root):
            level = root.replace(str(media_root), '').count(os.sep)
            indent = ' ' * 2 * level
            print(f"{indent}{os.path.basename(root)}/")
            subindent = ' ' * 2 * (level + 1)
            for file in files[:5]:  # Show first 5 files per directory
                print(f"{subindent}{file}")
            if len(files) > 5:
                print(f"{subindent}... and {len(files) - 5} more files")
    
    return missing_files

def create_production_sync_script():
    """Create a script to sync missing files"""
    script_content = '''#!/bin/bash
# Production Media Sync Script

echo "🚀 Syncing media files to production..."

# Create media directory structure
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/selfies
mkdir -p /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/kyc/id_documents
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 permissions
chmod -R 755 /home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/

echo "✅ Media directories created"

# You need to upload your local media files to production
# Example: scp -r ./media/* user@server:/home/acbptxvs/public_html/branchbusinessadvance.co.ke/media/

echo "📁 Upload your local media files to complete the sync"
'''
    
    with open('production_media_sync.sh', 'w', encoding='utf-8') as f:
        f.write(script_content)
    
    print("📝 Created production_media_sync.sh")

def main():
    print("🔧 HAVEN GRAZURI INVESTMENT LIMITED- Media Files Check")
    print("=" * 60)
    
    missing_files = check_media_files()
    create_production_sync_script()
    
    print(f"\n🎯 NEXT STEPS:")
    if missing_files:
        print("   1. Upload missing media files to production server")
        print("   2. Run production_media_sync.sh on production server")
        print("   3. Ensure file permissions are correct (755)")
        print("   4. Test image loading on website")
    else:
        print("   1. All media files exist locally")
        print("   2. Check production server file permissions")
        print("   3. Verify media URL routing")

if __name__ == "__main__":
    main()
