import rfeed
import datetime


from .common import SiteConfig
from .articles import ArticleMetadata, format_article_tags
from .templating import format_html_template



def build_blog_archive(
        index: dict[str, tuple[str, str]],
        page_template = 'templates/pages/default.html',
        li_template = 'templates/components/blog_archive_li.html',
        **kwargs
    ) -> str:
    '''Converts an index, formatted as filestem: (metadata, contents) dict,
    into an HTML page containing the list of articles, sorted from newest to oldest.
     
    Note: partials must be expanded into the kwargs, as they are needed to generate
    the overall page.
    '''

    # Add each article as a list item to an unordered list.
    archive_html_content = '<ul>'
    for article, (metadata, contents) in sorted(index.items(), key = lambda item: item[1][0].date)[::-1]:
        
        # Generate HTML for the article (including metadata tags).
        archive_html_content += format_html_template(
            li_template,
            article_filestem = article,
            blog_tags = ' '.join(format_article_tags(metadata.tags)),
            metadata = metadata
            
        )
    archive_html_content +='</ul>'

    # Interpolate the article into the overall page template.
    archive_html_page = format_html_template(
        page_template, 
        content = archive_html_content, 
        **kwargs
    )
        
    return archive_html_page

# TODO: Finish
def build_rss_feed(site: SiteConfig, index: dict[str, tuple[ArticleMetadata, str]]):
    feed = rfeed.Feed(
        title = site.title,
        link = f'{site.base_url.rstrip('/')}/rss.xml',
        description = site.description,
        language = "en-US",
        lastBuildDate = datetime.now(),
        items = [
            rfeed.Item(
                title = metadata.title,
                link = f'{site.base_url.rstrip('/')}/{filestem}.md', 
                description = metadata.description,
                author = metadata.author,
                guid = rfeed.Guid(filestem),
                pubDate = datetime(metadata.date.year, metadata.date.month, metadata.date.day)
            )
            for filestem, (metadata, _) in index.items()
        ]
    )

    # print(rss_feed.rss())