# # Standard Library Imports
import os
import time

# # Third-Party Library Imports
import requests

# # Django Imports
from django.shortcuts import render
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from .decorators import login_required

@login_required
def img_process(request):
    return render(request, 'img-upload.html')

MINIMAX_API_KEY = settings.MINIMAX_API_KEY
VIDEO_GEN_URL = "https://api.minimax.io/v1/video_generation"
QUERY_URL = "https://api.minimax.io/v1/query/video_generation"
FILES_URL = "https://api.minimax.io/v1/files/retrieve"
POLL_INTERVAL = 5  # seconds


@csrf_exempt
def process_images(request):
    if request.method != "POST":
        return JsonResponse({"error": "Invalid request method."}, status=405)

    first_frame = request.FILES.get("first_frame")
    last_frame = request.FILES.get("last_frame")

    if not first_frame or not last_frame:
        return JsonResponse({"error": "Both first_frame and last_frame are required."}, status=400)

    try:
        # --- Save uploaded images locally ---
        first_path = default_storage.save(f"uploads/{first_frame.name}", first_frame)
        last_path = default_storage.save(f"uploads/{last_frame.name}", last_frame)

        first_filename = os.path.basename(first_path)
        last_filename = os.path.basename(last_path)

        # --- Build public URLs using ngrok ---
        # Replace this with your current ngrok URL
        NGROK_URL = "https://postcartilaginous-kyler-nonrun.ngrok-free.dev"
        first_url = f"{NGROK_URL}{settings.MEDIA_URL}{first_filename}"
        last_url = f"{NGROK_URL}{settings.MEDIA_URL}{last_filename}"

        # --- Call MiniMax API ---
        headers = {"Authorization": f"Bearer {MINIMAX_API_KEY}"}
        payload = {
            "prompt": "Generate a smooth transition between two frames.",
            "first_frame_image": first_url,
            "last_frame_image": last_url,
            "model": "MiniMax-Hailuo-02",
            "duration": 6,
            "resolution": "1080P"
        }

        response = requests.post(VIDEO_GEN_URL, headers=headers, json=payload)
        response.raise_for_status()
        print("Response", response.json())
        task_id = response.json().get("task_id")
        if not task_id:
            return JsonResponse({"error": "Failed to get task_id from MiniMax API."}, status=500)

        # --- Poll MiniMax until task completes ---
        file_id = None
        while not file_id:
            time.sleep(POLL_INTERVAL)
            status_resp = requests.get(QUERY_URL, headers=headers, params={"task_id": task_id})
            status_resp.raise_for_status()
            status_data = status_resp.json()
            status = status_data.get("status")
            if status == "Success":
                file_id = status_data.get("file_id")
            elif status == "Fail":
                return JsonResponse({"error": status_data.get("error_message", "Video generation failed")}, status=500)

        # --- Get final video download URL ---
        download_resp = requests.get(FILES_URL, headers=headers, params={"file_id": file_id})
        download_resp.raise_for_status()
        download_url = download_resp.json()["file"]["download_url"]

        return JsonResponse({"video_url": download_url})

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