from django.conf import settings
from django.shortcuts import render
from django.views.decorators.csrf import ensure_csrf_cookie

from .models import Dress


def _context():
    dresses = Dress.objects.filter(is_active=True).exclude(image="").exclude(thumbnail="")
    used = set(dresses.values_list("category", flat=True))
    categories = [(k, v) for k, v in Dress.CATEGORY_CHOICES if k in used]
    # The browser must wait LONGER than the website waits for the AI server, or it gives up first.
    waits = {
        "fashn": settings.FASHN_TIMEOUT,
        "openai": settings.OPENAI_TIMEOUT,
        "gemini": settings.GEMINI_TIMEOUT,
        "grok": settings.XAI_TIMEOUT,
        "claude_grok": settings.CLAUDE_TIMEOUT + settings.XAI_TIMEOUT,
    }
    timeout_ms = (waits[settings.TRYON_ENGINE] + 120) * 1000 if settings.TRYON_ENGINE in waits else 180000
    return {"dresses": dresses, "categories": categories, "engine": settings.TRYON_ENGINE, "timeout_ms": timeout_ms,
            "capture_mode": settings.CAPTURE_MODE}


@ensure_csrf_cookie  # make sure the browser gets a CSRF cookie for the API calls
def index(request):
    """Photo mode: capture one photo, get an edited photo wearing the chosen dress."""
    return render(request, "catalog/photo.html", _context())


@ensure_csrf_cookie
def live(request):
    """Live video mode (experimental)."""
    return render(request, "catalog/live.html", _context())
