// Generate RSS feed from blog posts
async function generateRSSFeed() {
    try {
        const response = await fetch('/blog/blog-posts.json');
        const posts = await response.json();
        
        // Sort posts by date (newest first)
        const sortedPosts = posts.sort((a, b) => new Date(b.date) - new Date(a.date));
        
        // Build RSS XML
        const rssItems = sortedPosts.map(post => {
            // Escape HTML in content for XML
            const escapeXml = (str) => {
                return str.replace(/&/g, '&amp;')
                          .replace(/</g, '&lt;')
                          .replace(/>/g, '&gt;')
                          .replace(/"/g, '&quot;')
                          .replace(/'/g, '&apos;');
            };
            
            const content = escapeXml(post.content);
            const title = escapeXml(post.title);
            const excerpt = escapeXml(post.excerpt);
            const pubDate = new Date(post.date).toUTCString();
            
            return `    <item>
        <title>${title}</title>
        <link>https://example.com/blogpost.html?id=${post.id}</link>
        <guid>https://example.com/blogpost.html?id=${post.id}</guid>
        <pubDate>${pubDate}</pubDate>
        <description><![CDATA[${excerpt}<br/><br/>${content}]]></description>
    </item>`;
        }).join('\n');
        
        const rssXml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>My Blog</title>
        <link>https://example.com/blog</link>
        <description>Blog posts</description>
        <language>en-us</language>
        <lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
        <atom:link href="https://example.com/blog/feed.xml" rel="self" type="application/rss+xml"/>
${rssItems}
    </channel>
</rss>`;
        
        return rssXml;
    } catch (error) {
        console.error('Error generating RSS feed:', error);
        return null;
    }
}

// If this script is run directly (not imported), generate and serve the feed
if (typeof window === 'undefined') {
    // Node.js environment - generate RSS file
    const fs = require('fs');
    const path = require('path');
    
    async function writeRSSFile() {
        const posts = JSON.parse(fs.readFileSync(path.join(__dirname, 'blog-posts.json'), 'utf8'));
        const sortedPosts = posts.sort((a, b) => new Date(b.date) - new Date(a.date));
        
        const escapeXml = (str) => {
            return str.replace(/&/g, '&amp;')
                      .replace(/</g, '&lt;')
                      .replace(/>/g, '&gt;')
                      .replace(/"/g, '&quot;')
                      .replace(/'/g, '&apos;');
        };
        
        const rssItems = sortedPosts.map(post => {
            const content = escapeXml(post.content);
            const title = escapeXml(post.title);
            const excerpt = escapeXml(post.excerpt);
            const pubDate = new Date(post.date).toUTCString();
            
            return `    <item>
        <title>${title}</title>
        <link>https://example.com/blogpost.html?id=${post.id}</link>
        <guid>https://example.com/blogpost.html?id=${post.id}</guid>
        <pubDate>${pubDate}</pubDate>
        <description><![CDATA[${excerpt}<br/><br/>${content}]]></description>
    </item>`;
        }).join('\n');
        
        const rssXml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>My Blog</title>
        <link>https://example.com/blog</link>
        <description>Blog posts</description>
        <language>en-us</language>
        <lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
        <atom:link href="https://example.com/blog/feed.xml" rel="self" type="application/rss+xml"/>
${rssItems}
    </channel>
</rss>`;
        
        fs.writeFileSync(path.join(__dirname, 'feed.xml'), rssXml, 'utf8');
        console.log('RSS feed generated successfully');
    }
    
    writeRSSFile();
}
