"""
RSS and Atom feeds for Django Lotus Extras.

Provides syndication feeds for blog articles, allowing users to subscribe
and stay updated with new content.
"""
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed

from .conf import django_blog_plus_settings


def get_article_model():
    """Lazy import of Article model to avoid import-time Django configuration issues."""
    try:
        from lotus.models import Article
        return Article
    except ImportError:
        return None


def get_status_published():
    """Get the published status value."""
    try:
        from lotus.choices import STATUS_PUBLISHED
        return STATUS_PUBLISHED
    except ImportError:
        return 10  # Default fallback


class LatestArticlesFeed(Feed):
    """RSS 2.0 feed for the latest blog articles."""

    @property
    def title(self):
        return django_blog_plus_settings.SITE_NAME

    @property
    def description(self):
        return django_blog_plus_settings.SITE_DESCRIPTION or f"Latest articles from {django_blog_plus_settings.SITE_NAME}"

    link = "/blog/"

    def items(self):
        """Return the 20 most recent published articles."""
        Article = get_article_model()
        if Article is None:
            return []

        language = django_blog_plus_settings.get_language_code()
        return Article.objects.filter(
            language=language,
            status=get_status_published(),
        ).order_by('-publish_date', '-publish_time')[:20]

    def item_title(self, item):
        """Return the article title."""
        return item.title

    def item_description(self, item):
        """Return the article introduction or lead."""
        if item.introduction:
            return item.introduction
        elif item.lead:
            return item.lead
        return ""

    def item_link(self, item):
        """Return the absolute URL to the article."""
        return item.get_absolute_url()

    def item_pubdate(self, item):
        """Return the publish datetime."""
        return item.publish_datetime()

    def item_author_name(self, item):
        """Return the first author's name."""
        authors = item.get_authors()
        if authors:
            return authors[0].get_full_name()
        return None

    def item_categories(self, item):
        """Return the article's categories as a list."""
        categories = item.get_categories()
        return [cat.title for cat in categories]


class LatestArticlesAtomFeed(LatestArticlesFeed):
    """Atom 1.0 feed for the latest blog articles."""

    feed_type = Atom1Feed
    
    @property
    def subtitle(self):
        return self.description


class CategoryFeed(Feed):
    """RSS feed for articles in a specific category."""

    def get_object(self, request, slug):
        """Get the category from the slug."""
        try:
            from lotus.models import Category
            language = django_blog_plus_settings.get_language_code()
            return Category.objects.get(slug=slug, language=language)
        except ImportError:
            return None

    def title(self, obj):
        """Return the feed title for this category."""
        if obj:
            return f"{obj.title} - {django_blog_plus_settings.SITE_NAME}"
        return django_blog_plus_settings.SITE_NAME

    def link(self, obj):
        """Return the category URL."""
        if obj:
            return obj.get_absolute_url()
        return "/blog/"

    def description(self, obj):
        """Return the category description."""
        if obj and obj.description:
            return obj.description
        return f"Latest articles in {obj.title if obj else 'this category'}"

    def items(self, obj):
        """Return articles in this category."""
        Article = get_article_model()
        if not obj or Article is None:
            return []

        return Article.objects.filter(
            categories=obj,
            status=get_status_published(),
        ).order_by('-publish_date', '-publish_time')[:20]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        if item.introduction:
            return item.introduction
        elif item.lead:
            return item.lead
        return ""

    def item_link(self, item):
        return item.get_absolute_url()

    def item_pubdate(self, item):
        return item.publish_datetime()
