# home/api/pages.py

from django.http import JsonResponse
from django.views.decorators.http import require_GET
from django.core.cache import cache
from django.conf import settings
from wagtail.models import Page, Site

from .permissions import tenant_api_protected
from .rate_limit import tenant_rate_limited
from .pagination import paginate_queryset
from .utils import build_absolute_media_url


CACHE_KEY_PREFIX = "pages_api_v1"
CACHE_TTL = getattr(settings, "TENANT_CACHE_TTL", 60 * 5)


# =========================
# Serializer
# =========================
def _page_to_dict(request, page):
    """
    Generic page serializer (safe for all Page subclasses)
    """
    featured_image = getattr(page, "featured_image", None)

    return {
        "id": page.id,
        "title": page.title,
        "slug": page.slug,
        "url": page.url,
        "last_published": page.last_published_at,
        "featured_image": (
            build_absolute_media_url(request, featured_image.file.url)
            if featured_image
            else None
        ),
    }


# =========================
# Page List API (paginated)
# =========================
@require_GET
@tenant_rate_limited
@tenant_api_protected
def page_list_api(request):
    site = Site.find_for_request(request)
    if not site:
        return JsonResponse({"detail": "Site not resolved"}, status=404)

    page_param = request.GET.get("page", "1")
    size_param = request.GET.get("page_size", "10")

    cache_key = (
        f"{CACHE_KEY_PREFIX}:list:"
        f"site:{site.id}:{site.hostname}:"
        f"page:{page_param}:size:{size_param}"
    )

    cached = cache.get(cache_key)
    if cached:
        return JsonResponse(cached)

    queryset = (
        Page.objects
        .live()
        .public()
        .descendant_of(site.root_page)
        .specific()
        .order_by("path")
    )

    meta, items = paginate_queryset(queryset, request)

    data = {
        "meta": meta,
        "items": [_page_to_dict(request, p) for p in items],
    }

    cache.set(cache_key, data, timeout=CACHE_TTL)
    return JsonResponse(data)


# =========================
# Page Detail API
# =========================
@require_GET
@tenant_rate_limited
@tenant_api_protected
def page_detail_api(request, slug):
    site = Site.find_for_request(request)
    if not site:
        return JsonResponse({"detail": "Site not resolved"}, status=404)

    cache_key = f"{CACHE_KEY_PREFIX}:detail:{slug}:site:{site.id}:{site.hostname}"

    cached = cache.get(cache_key)
    if cached:
        return JsonResponse(cached)

    try:
        page = (
            Page.objects
            .live()
            .public()
            .descendant_of(site.root_page)
            .get(slug=slug)
            .specific
        )
    except Page.DoesNotExist:
        return JsonResponse({"detail": "Page not found"}, status=404)

    data = {
        **_page_to_dict(request, page),
        "seo": {
            "title": getattr(page, "seo_title", None),
            "description": getattr(page, "search_description", None),
        },
    }

    cache.set(cache_key, data, timeout=CACHE_TTL)
    return JsonResponse(data)