import {readFile,writeFile} from 'node:fs/promises';import {join} from 'node:path';
const root=process.cwd(),out=join(root,process.argv[2]||'dist'),posts=JSON.parse(await readFile(join(root,'content/posts.json'),'utf8')),config=JSON.parse(await readFile(join(root,'content/site-config.json'),'utf8')),base=config.brand.url.replace(/\/$/,'');
const published=posts.filter(p=>p.status==='published');
const urls=[`${base}/`,`${base}/license.html`,...published.flatMap(p=>[`${base}/posts/${p.slug}/`,`${base}/ja/posts/${p.slug}/`])];
const sitemap=`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.map((u,i)=>`  <url><loc>${u}</loc>${i>1?`<lastmod>${published[Math.floor((i-2)/2)].dateModified}</lastmod>`:''}</url>`).join('\n')}\n</urlset>\n`;
await writeFile(join(out,'sitemap.xml'),sitemap);
await writeFile(join(out,'robots.txt'),`User-agent: *\nAllow: /\nSitemap: ${base}/sitemap.xml\n`);
const rss=`<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0"><channel><title>${config.brand.name}</title><link>${base}/</link><description>Latest posts from ${config.brand.name}</description><language>en-gb</language>${published.map(p=>`<item><title><![CDATA[${p.title.en}]]></title><link>${base}/posts/${p.slug}/</link><guid>${base}/posts/${p.slug}/</guid><pubDate>${new Date(p.datePublished+'T12:00:00Z').toUTCString()}</pubDate><description><![CDATA[${p.excerpt.en}]]></description><category><![CDATA[${p.section.en}]]></category></item>`).join('')}</channel></rss>`;
await writeFile(join(out,'rss.xml'),rss);
await writeFile(join(out,'feed.json'),JSON.stringify({version:'https://jsonfeed.org/version/1.1',title:config.brand.name,home_page_url:`${base}/`,feed_url:`${base}/feed.json`,items:published.map(p=>({id:`${base}/posts/${p.slug}/`,url:`${base}/posts/${p.slug}/`,title:p.title.en,summary:p.excerpt.en,date_published:`${p.datePublished}T12:00:00Z`,date_modified:`${p.dateModified}T12:00:00Z`,image:`${base}/assets/img/calling-cards/${p.slug}/social-1200x630.png`,tags:[p.section.en]}))},null,2));
console.log('Generated sitemap, robots, RSS and JSON Feed.');
