#!/usr/bin/env python3
"""
Deploy Media Files to Production
Creates deployment commands for uploading media files to production server
"""

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 create_deployment_commands():
    """Create commands to deploy media files to production"""
    
    print("🚀 Creating production media deployment commands...")
    
    # Get all unique media files from database
    media_files = set()
    
    users = CustomUser.objects.all()
    for user in users:
        # Check all document fields
        document_fields = [
            user.selfie,
            user.id_document,
            user.utility_bill,
            user.bank_statement,
            user.business_license,
            user.tax_certificate,
            user.logbook,
            user.title_deed,
            user.signature,
            user.profile_image,
        ]
        
        for field_value in document_fields:
            if field_value:
                media_files.add(field_value.name)
    
    # Create deployment script
    deployment_script = '''#!/bin/bash
# Media Files Deployment Script for Production

echo "🚀 Deploying media files to production server..."

# Production server details
PROD_SERVER="/home/acbptxvs/public_html/branchbusinessadvance.co.ke"
MEDIA_DIR="$PROD_SERVER/media"

# Create media directory structure
echo "📁 Creating media directories..."
mkdir -p "$MEDIA_DIR/kyc/selfies"
mkdir -p "$MEDIA_DIR/kyc/id_documents"
mkdir -p "$MEDIA_DIR/kyc/bank_statements"
mkdir -p "$MEDIA_DIR/kyc/business_licenses"
mkdir -p "$MEDIA_DIR/kyc/signatures"
mkdir -p "$MEDIA_DIR/kyc/utility_bills"
mkdir -p "$MEDIA_DIR/kyc/tax_certificates"
mkdir -p "$MEDIA_DIR/kyc/title_deeds"
mkdir -p "$MEDIA_DIR/kyc/logbooks"
mkdir -p "$MEDIA_DIR/profile_images"
mkdir -p "$MEDIA_DIR/receipts"

echo "✅ Media directories created"

# Copy local media files to production
echo "📤 Copying media files..."
if [ -d "./media" ]; then
    cp -r ./media/* "$MEDIA_DIR/"
    echo "✅ Media files copied"
else
    echo "❌ Local media directory not found"
fi

# Set proper permissions
echo "🔒 Setting file permissions..."
chmod -R 755 "$MEDIA_DIR"
find "$MEDIA_DIR" -type f -exec chmod 644 {} \\;

echo "✅ Permissions set"

# Verify deployment
echo "🔍 Verifying deployment..."
echo "Media directory size: $(du -sh $MEDIA_DIR 2>/dev/null || echo 'Directory not found')"
echo "Total files: $(find $MEDIA_DIR -type f 2>/dev/null | wc -l || echo '0')"

echo "🎉 Media deployment completed!"
'''
    
    with open('deploy_media_production.sh', 'w') as f:
        f.write(deployment_script)
    
    os.chmod('deploy_media_production.sh', 0o755)
    
    # Create a Python script to check missing files
    check_script = f'''#!/usr/bin/env python3
"""
Check missing media files on production
Run this on the production server
"""

import os
from pathlib import Path

# Production media files that should exist
REQUIRED_FILES = {repr(sorted(media_files))}

MEDIA_ROOT = "/home/acbptxvs/public_html/branchbusinessadvance.co.ke/media"

def check_files():
    missing = []
    existing = []
    
    for file_path in REQUIRED_FILES:
        full_path = os.path.join(MEDIA_ROOT, file_path)
        if os.path.exists(full_path):
            existing.append(file_path)
        else:
            missing.append(file_path)
    
    print(f"📊 MEDIA FILES CHECK:")
    print(f"   • Total required: {{len(REQUIRED_FILES)}}")
    print(f"   • Existing: {{len(existing)}}")
    print(f"   • Missing: {{len(missing)}}")
    
    if missing:
        print(f"\\n❌ MISSING FILES:")
        for file in missing[:10]:
            print(f"   • {{file}}")
        if len(missing) > 10:
            print(f"   ... and {{len(missing) - 10}} more")
    
    return missing

if __name__ == "__main__":
    check_files()
'''
    
    with open('check_production_media.py', 'w') as f:
        f.write(check_script)
    
    print(f"📝 Created deployment scripts:")
    print(f"   • deploy_media_production.sh - Run on production server")
    print(f"   • check_production_media.py - Verify files after deployment")
    print(f"   • Found {len(media_files)} unique media files in database")

def main():
    print("🔧 HAVEN GRAZURI INVESTMENT LIMITED- Media Deployment")
    print("=" * 60)
    
    create_deployment_commands()
    
    print(f"\n🎯 DEPLOYMENT STEPS:")
    print("   1. Upload your local 'media' folder to production server")
    print("   2. Run: bash deploy_media_production.sh")
    print("   3. Run: python3 check_production_media.py")
    print("   4. Test image loading on website")
    print("\n💡 Alternative: Use cPanel File Manager to upload media files")

if __name__ == "__main__":
    main()
