from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from django.db.models import Count
from hub.services.models import (
    Service,
    ServiceOffering,
    CloudProvider,
)


def provider_list(request):
    providers = (
        CloudProvider.objects.filter(disable_listing=False)
        .order_by("order")
        .prefetch_related("offerings", "consulting_partners")
    )

    # Handle search
    if request.GET.get("search"):
        query = request.GET.get("search")
        providers = providers.filter(
            Q(name__icontains=query) | Q(description__icontains=query)
        )

    context = {
        "providers": providers,
    }
    return render(request, "services/provider_list.html", context)


def provider_detail(request, slug):
    provider = get_object_or_404(
        CloudProvider.objects.prefetch_related(
            "offerings",
            "offerings__service",
            "offerings__plans",
            "consulting_partners",
        ),
        slug=slug,
    )

    # Get all services offered by this provider through offerings
    services = (
        Service.objects.filter(
            offerings__cloud_provider=provider, disable_listing=False
        )
        .distinct()
        .prefetch_related("categories")
    )

    # Get the provider's offerings and sort them by service attributes and plan availability
    # Exclude offerings with disabled services
    ordered_offerings = (
        ServiceOffering.objects.filter(
            cloud_provider=provider, service__disable_listing=False
        )
        .select_related("service")
        .annotate(has_plans=Count("plans"))
        .order_by(
            "-has_plans",  # Offerings with plans first
            "-service__is_featured",  # Featured first (True before False)
            "service__is_coming_soon",  # Coming soon last (False before True)
            "service__name",  # Alphabetically within each group
        )
    )

    context = {
        "provider": provider,
        "services": services,
        "ordered_offerings": ordered_offerings,
    }
    return render(request, "services/provider_detail.html", context)
