#!/usr/bin/env node
// Script to generate RSS feed from blog-posts.json
const fs = require('fs');
const path = require('path');

const postsPath = path.join(__dirname, 'blog-posts.json');
const feedPath = path.join(__dirname, 'feed.xml');

try {
    const posts = JSON.parse(fs.readFileSync(postsPath, 'utf8'));
    
    // Sort posts by date (newest first)
    const sortedPosts = posts.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    // Escape XML special characters
    const escapeXml = (str) => {
        if (!str) return '';
        return str.toString()
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&apos;');
    };
    
    // Convert content newlines to HTML breaks
    const formatContent = (content) => {
        return content.split('\n\n')
            .map(p => p.trim())
            .filter(p => p.length > 0)
            .join('<br/><br/>');
    };
    
    // Generate RSS items
    const rssItems = sortedPosts.map(post => {
        const title = escapeXml(post.title);
        const excerpt = escapeXml(post.excerpt);
        const content = formatContent(post.content);
        const pubDate = new Date(post.date + 'T00:00:00Z').toUTCString();
        const link = `https://example.com/blog/post.html?id=${post.id}`;
        
        return `        <item>
            <title>${title}</title>
            <link>${link}</link>
            <guid>${link}</guid>
            <pubDate>${pubDate}</pubDate>
            <description><![CDATA[${excerpt}<br/><br/>${content}]]></description>
        </item>`;
    }).join('\n');
    
    // Generate RSS XML
    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/api/feed.php" rel="self" type="application/rss+xml"/>
${rssItems}
    </channel>
</rss>`;
    
    // Write RSS feed file
    fs.writeFileSync(feedPath, rssXml, 'utf8');
    console.log('RSS feed generated successfully at', feedPath);
} catch (error) {
    console.error('Error generating RSS feed:', error);
    process.exit(1);
}
