from django.contrib.sitemaps import Sitemap
from django.db.models import Count, Max
from django.urls import reverse
from taggit.models import Tag

from apps.core.seo import site_url

from .models import Article, Category


class SiteSitemap(Sitemap):
    """
    Build every URL from settings.SITE_URL.

    The old sitemap used the Sites table, whose domain was saved as
    "https://thereversetimes.com/" — producing broken links like
    https://https://thereversetimes.com//articles/... that Google rejects.
    """
    protocol = 'https'

    def get_domain(self, site=None):
        return site_url().split('://', 1)[-1]

    def get_protocol(self, protocol=None):
        return site_url().split('://', 1)[0]


class ArticleSitemap(SiteSitemap):
    """All published articles — highest priority."""
    changefreq = 'weekly'
    priority = 0.9

    def items(self):
        return Article.objects.filter(status='published').order_by('-published_at')

    def lastmod(self, obj):
        return obj.updated_at

    def location(self, obj):
        return reverse('article_detail', kwargs={'slug': obj.slug})


class CategorySitemap(SiteSitemap):
    changefreq = 'daily'
    priority = 0.7

    def items(self):
        return (Category.objects.filter(is_active=True)
                .annotate(latest=Max('articles__updated_at')).order_by('order'))

    def lastmod(self, obj):
        return obj.latest

    def location(self, obj):
        return reverse('category_detail', kwargs={'slug': obj.slug})


class TagSitemap(SiteSitemap):
    """Only tags with 2+ articles; single-article tag pages are thin duplicates."""
    changefreq = 'weekly'
    priority = 0.4

    def items(self):
        return (Tag.objects.filter(article__status='published')
                .annotate(n=Count('article', distinct=True)).filter(n__gte=2).order_by('slug'))

    def location(self, obj):
        return reverse('tag_detail', kwargs={'slug': obj.slug})


class StaticViewSitemap(SiteSitemap):
    """Core pages. /articles/ is left out: it shows the same content as the homepage."""
    changefreq = 'weekly'

    def items(self):
        return ['home', 'magazine', 'shop', 'shop_merch', 'shop_nostalgic', 'games', 'about', 'team', 'contact', 'submit',
                '/terms-and-conditions/', '/privacy-policy/']

    def priority(self, item):
        if item.startswith('/'):
            return 0.3  # legal pages
        return {'home': 1.0, 'magazine': 0.9, 'shop': 0.9}.get(item, 0.7)

    def location(self, item):
        return item if item.startswith('/') else reverse(item)


class ProductSitemap(SiteSitemap):
    changefreq = 'weekly'
    priority = 0.6

    def items(self):
        from apps.store.models import Product
        return Product.objects.filter(is_active=True, product_type__in=['merch', 'nostalgic']).order_by('-created_at')

    def lastmod(self, obj):
        return obj.updated_at or obj.created_at

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


class MagazineSitemap(SiteSitemap):
    """Magazine issues at /magazine/<issue>/."""
    changefreq = 'monthly'
    priority = 0.9

    def items(self):
        from apps.store.models import Product
        return Product.objects.filter(is_active=True, product_type='magazine').order_by('-created_at')

    def lastmod(self, obj):
        return obj.updated_at or obj.created_at

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


class GameSitemap(SiteSitemap):
    """History games at /games/<game>/."""
    changefreq = 'monthly'
    priority = 0.7

    def items(self):
        from apps.games.models import Game
        return Game.objects.filter(is_active=True)

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