import os
import requests
from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse
from .models import VideoTask
from .video_engine import generate_video
import threading

def home(request):
    # Fetch surahs and reciters for the form
    surahs = []
    reciters = []
    try:
        surah_resp = requests.get("https://api.alquran.cloud/v1/surah", timeout=5)
        if surah_resp.status_code == 200:
            surahs = surah_resp.json()['data']
        
        reciter_resp = requests.get("https://api.alquran.cloud/v1/edition?format=audio&language=ar&type=versebyverse", timeout=5)
        if reciter_resp.status_code == 200:
            reciters = reciter_resp.json()['data']
    except:
        pass

    backgrounds = []
    if os.path.exists('backgrounds'):
        backgrounds = [f for f in os.listdir('backgrounds') if f.endswith(('.mp4', '.mov'))]
    
    if not backgrounds:
        backgrounds = ["nature.mp4"]

    tasks = VideoTask.objects.all().order_by('-created_at')[:10]

    context = {
        "surahs": surahs,
        "reciters": reciters,
        "backgrounds": backgrounds,
        "tasks": tasks,
        "project_name": "Quran Reels Gen",
    }
    return render(request, "core/index.html", context)

def generate_video_view(request):
    if request.method == "POST":
        surah_number = request.POST.get('surah')
        reciter = request.POST.get('reciter')
        verse_start = request.POST.get('verse_start')
        verse_end = request.POST.get('verse_end')
        background = request.POST.get('background')
        text_color = request.POST.get('text_color', '#FFFFFF')

        # Get surah name
        surah_name = "Unknown"
        try:
            surah_resp = requests.get(f"https://api.alquran.cloud/v1/surah/{surah_number}", timeout=5)
            if surah_resp.status_code == 200:
                surah_name = surah_resp.json()['data']['englishName']
        except:
            pass

        task = VideoTask.objects.create(
            surah_number=surah_number,
            surah_name=surah_name,
            reciter_identifier=reciter,
            reciter_name=reciter,
            verse_start=verse_start,
            verse_end=verse_end,
            background_video=background,
            text_color=text_color,
            status='pending'
        )

        # Run generation in background thread
        thread = threading.Thread(target=generate_video, args=(task.id,))
        thread.start()

        return redirect('home')
    return redirect('home')

def get_surah_details(request, surah_number):
    try:
        resp = requests.get(f"https://api.alquran.cloud/v1/surah/{surah_number}", timeout=5)
        if resp.status_code == 200:
            return JsonResponse(resp.json()['data'])
    except:
        pass
    return JsonResponse({'error': 'Failed to fetch'}, status=400)
