import os

from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Rss201rev2Feed
from django.utils.html import strip_tags

from .models import ArticlePage


def _get_env_int(name, default):
    value = os.environ.get(name)
    if value is None:
        return default
    try:
        parsed = int(value)
    except ValueError:
        return default
    return parsed if parsed > 0 else default


ARTICLE_FEED_SIZE = _get_env_int("ARTICLE_FEED_SIZE", 50)


class LatestArticlesFeed(Feed):
    feed_type = Rss201rev2Feed
    title = "DeBuT AI 最新文章"
    link = "/"
    description = "DeBuT AI 最新文章 RSS feed"

    def items(self):
        return ArticlePage.objects.live().order_by("-date", "-id")[:ARTICLE_FEED_SIZE]

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

    def item_description(self, item):
        return strip_tags(item.intro or item.search_description or "")

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

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

    def item_categories(self, item):
        return list(item.tags.values_list("name", flat=True))
