from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from hub.services.models import ConsultingPartner, CloudProvider, Service


def partner_list(request):
    # Get basic filter parameters
    search_query = request.GET.get("search", "")
    service_id = request.GET.get("service", "")
    cloud_provider_id = request.GET.get("cloud_provider", "")

    # Start with all active partners
    partners = ConsultingPartner.objects.filter(disable_listing=False).order_by("order")

    # Apply filters based on request parameters
    if search_query:
        partners = partners.filter(
            Q(name__icontains=search_query) | Q(description__icontains=search_query)
        )

    if service_id:
        partners = partners.filter(services__id=service_id)

    if cloud_provider_id:
        partners = partners.filter(cloud_providers__id=cloud_provider_id)

    # Get available services from filtered partners
    available_service_ids = partners.values_list("services__id", flat=True).distinct()
    available_services = Service.objects.filter(
        id__in=available_service_ids, disable_listing=False
    ).order_by("name")

    # Get available cloud providers from filtered partners
    available_cloud_provider_ids = partners.values_list(
        "cloud_providers__id", flat=True
    ).distinct()
    available_cloud_providers = CloudProvider.objects.filter(
        id__in=available_cloud_provider_ids, disable_listing=False
    ).order_by("order")

    # For the current selection, we need to make sure we include the selected items
    # even if they don't match other filters
    if service_id:
        try:
            selected_service_id = int(service_id)
            if selected_service_id not in available_service_ids:
                selected_service = Service.objects.get(id=selected_service_id)
                available_services = list(available_services)
                available_services.append(selected_service)
        except (ValueError, Service.DoesNotExist):
            pass

    if cloud_provider_id:
        try:
            cp_id = int(cloud_provider_id)
            if cp_id not in available_cloud_provider_ids:
                selected_provider = CloudProvider.objects.get(id=cp_id)
                available_cloud_providers = list(available_cloud_providers)
                available_cloud_providers.append(selected_provider)
        except (ValueError, CloudProvider.DoesNotExist):
            pass

    context = {
        "partners": partners.prefetch_related("services", "cloud_providers"),
        "services": Service.objects.filter(disable_listing=False).order_by("name"),
        "cloud_providers": CloudProvider.objects.filter(disable_listing=False).order_by(
            "order"
        ),
        "available_services": available_services,
        "available_cloud_providers": available_cloud_providers,
    }
    return render(request, "services/partner_list.html", context)


def partner_detail(request, slug):
    partner = get_object_or_404(
        ConsultingPartner.objects.prefetch_related(
            "services",
            "services__categories",
            "services__offerings",
            "services__offerings__cloud_provider",
            "cloud_providers",
        ),
        slug=slug,
    )

    context = {
        "partner": partner,
        "services": partner.services.all(),
    }
    return render(request, "services/partner_detail.html", context)
