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


def article_list(request):
    """View for listing articles with filtering capabilities"""
    # Get basic filter parameters
    search_query = request.GET.get("search", "")
    service_id = request.GET.get("service", "")
    consulting_partner_id = request.GET.get("consulting_partner", "")
    cloud_provider_id = request.GET.get("cloud_provider", "")

    # Start with all published articles
    all_articles = Article.objects.filter(is_published=True)
    articles = all_articles

    # Apply filters based on request parameters
    if search_query:
        articles = articles.filter(
            Q(title__icontains=search_query)
            | Q(excerpt__icontains=search_query)
            | Q(content__icontains=search_query)
            | Q(meta_keywords__icontains=search_query)
        )

    if service_id:
        articles = articles.filter(related_service__id=service_id)

    if consulting_partner_id:
        articles = articles.filter(related_consulting_partner__id=consulting_partner_id)

    if cloud_provider_id:
        articles = articles.filter(related_cloud_provider__id=cloud_provider_id)

    # Order articles: featured first, then by creation date (newest first)
    articles = articles.order_by(
        "-is_featured",  # Featured first (True before False)
        "-article_date",  # Newest first
    )

    # Create base querysets for each filter type that apply all OTHER current filters
    # This way, each filter shows options that would return results if selected

    # For service filter options, apply all other filters except service
    service_filter_base = all_articles
    if search_query:
        service_filter_base = service_filter_base.filter(
            Q(title__icontains=search_query)
            | Q(excerpt__icontains=search_query)
            | Q(content__icontains=search_query)
            | Q(meta_keywords__icontains=search_query)
        )
    if consulting_partner_id:
        service_filter_base = service_filter_base.filter(
            related_consulting_partner__id=consulting_partner_id
        )
    if cloud_provider_id:
        service_filter_base = service_filter_base.filter(
            related_cloud_provider__id=cloud_provider_id
        )

    # For consulting partner filter options, apply all other filters except consulting_partner
    cp_filter_base = all_articles
    if search_query:
        cp_filter_base = cp_filter_base.filter(
            Q(title__icontains=search_query)
            | Q(excerpt__icontains=search_query)
            | Q(content__icontains=search_query)
            | Q(meta_keywords__icontains=search_query)
        )
    if service_id:
        cp_filter_base = cp_filter_base.filter(related_service__id=service_id)
    if cloud_provider_id:
        cp_filter_base = cp_filter_base.filter(
            related_cloud_provider__id=cloud_provider_id
        )

    # For cloud provider filter options, apply all other filters except cloud_provider
    cloud_filter_base = all_articles
    if search_query:
        cloud_filter_base = cloud_filter_base.filter(
            Q(title__icontains=search_query)
            | Q(excerpt__icontains=search_query)
            | Q(content__icontains=search_query)
            | Q(meta_keywords__icontains=search_query)
        )
    if service_id:
        cloud_filter_base = cloud_filter_base.filter(related_service__id=service_id)
    if consulting_partner_id:
        cloud_filter_base = cloud_filter_base.filter(
            related_consulting_partner__id=consulting_partner_id
        )

    # Get available services, consulting partners and cloud providers that would return results if selected
    available_services = Service.objects.filter(
        disable_listing=False,
        id__in=service_filter_base.values_list(
            "related_service__id", flat=True
        ).distinct(),
    ).distinct()

    available_consulting_partners = ConsultingPartner.objects.filter(
        disable_listing=False,
        id__in=cp_filter_base.values_list(
            "related_consulting_partner__id", flat=True
        ).distinct(),
    ).distinct()

    available_cloud_providers = CloudProvider.objects.filter(
        disable_listing=False,
        id__in=cloud_filter_base.values_list(
            "related_cloud_provider__id", flat=True
        ).distinct(),
    ).distinct()

    context = {
        "articles": articles,
        "available_services": available_services,
        "available_consulting_partners": available_consulting_partners,
        "available_cloud_providers": available_cloud_providers,
        "search_query": search_query,
    }

    return render(request, "services/article_list.html", context)


def article_detail(request, slug):
    """View for displaying article details"""
    article = get_object_or_404(
        Article.objects.select_related(
            "author",
            "related_service",
            "related_consulting_partner",
            "related_cloud_provider",
        ).filter(is_published=True),
        slug=slug,
    )

    # Get related articles (same service, partner, or provider)
    related_articles = Article.objects.filter(is_published=True).exclude(id=article.id)

    if article.related_service:
        related_articles = related_articles.filter(
            related_service=article.related_service
        )
    elif article.related_consulting_partner:
        related_articles = related_articles.filter(
            related_consulting_partner=article.related_consulting_partner
        )
    elif article.related_cloud_provider:
        related_articles = related_articles.filter(
            related_cloud_provider=article.related_cloud_provider
        )
    else:
        # If no specific relation, get other general articles
        related_articles = related_articles.filter(
            related_service__isnull=True,
            related_consulting_partner__isnull=True,
            related_cloud_provider__isnull=True,
        )

    related_articles = related_articles.order_by("-article_date")[:3]

    context = {
        "article": article,
        "related_articles": related_articles,
    }
    return render(request, "services/article_detail.html", context)
