from urllib.parse import urlencode

from django.core.paginator import Paginator
from django.template.response import TemplateResponse
from django.db.models import Q

from wagtail.models import Site

from home.models import ArticlePage, PAGE_SIZE
from home.pagination import build_pagination_context, get_page_size


def search(request):
    search_query = (request.GET.get("query") or "").strip()
    page_number = request.GET.get("page", 1)
    category_sections = []
    results_page = None
    results_count = 0

    if search_query:
        primary_qs = ArticlePage.objects.live().search(search_query)
        results_count = primary_qs.count()

        if not results_count:
            fallback_filter = Q(intro__icontains=search_query) | Q(body__icontains=search_query)
            primary_qs = ArticlePage.objects.live().filter(fallback_filter).order_by("-date")
            results_count = primary_qs.count()

        if results_count:
            paginator = Paginator(primary_qs, get_page_size(request, PAGE_SIZE))
            results_page = paginator.get_page(page_number)
            query_string = urlencode({"query": search_query})
            category_sections = [
                {
                    "title": f"搜尋：{search_query}",
                    "items": results_page,
                    "url": f"{request.path}?{query_string}",
                    "pagination": build_pagination_context(request, results_page, paginator),
                }
            ]

    site = Site.find_for_request(request)
    site_root = site.root_page if site else None

    return TemplateResponse(
        request,
        "search/search.html",
        {
            "search_query": search_query,
            "category_sections": category_sections,
            "results_page": results_page,
            "results_count": results_count,
            "site_root": site_root,
            "page": site_root.specific if site_root else None,
        },
    )
