"""
Blog Sitemaps for SEO.

Provides XML sitemaps for blog articles and categories
to help search engines discover and index content.

Sitemap URLs use the request host (when set) so they match the canonical URL
on each page (scheme + request.get_host() + path), fixing "Non-canonical URL"
warnings in SEO tools.
"""
from django.contrib.sitemaps import Sitemap

from .conf import django_blog_plus_settings


class RequestHostSitemapMixin:
    """
    Mixin that makes sitemap URLs use the request host when available.
    This ensures sitemap <loc> matches the page's canonical URL exactly.
    """

    def get_domain(self, site=None):
        if getattr(self, '_request', None) is not None:
            return self._request.get_host()
        return super().get_domain(site)


class BlogArticleSitemap(RequestHostSitemapMixin, Sitemap):
    """
    XML Sitemap for blog articles.
    Includes all published articles with their last modification dates.
    """
    changefreq = 'weekly'
    priority = 0.8
    protocol = 'https'

    def items(self):
        from lotus.models import Article
        from lotus.choices import STATUS_PUBLISHED

        language = django_blog_plus_settings.get_language_code()

        return Article.objects.filter(
            language=language,
            status=STATUS_PUBLISHED
        ).order_by('-publish_date', '-publish_time')

    def lastmod(self, obj):
        return obj.last_update or obj.publish_datetime()

    def location(self, obj):
        return obj.get_absolute_url()


class BlogCategorySitemap(RequestHostSitemapMixin, Sitemap):
    """
    XML Sitemap for blog categories.
    """
    changefreq = 'weekly'
    priority = 0.6
    protocol = 'https'

    def items(self):
        from lotus.models import Category

        language = django_blog_plus_settings.get_language_code()

        return Category.objects.filter(language=language)

    def location(self, obj):
        return obj.get_absolute_url()


# Sitemaps dictionary for use in urls.py
sitemaps = {
    'blog-articles': BlogArticleSitemap,
    'blog-categories': BlogCategorySitemap,
}
