import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const DIST = path.join(ROOT, 'dist');

const SITE = 'https://pushkinohistory.ru';

const posts = JSON.parse(fs.readFileSync(path.join(ROOT, 'src/content/posts.json'), 'utf8'));
const pages = JSON.parse(fs.readFileSync(path.join(ROOT, 'src/content/pages.json'), 'utf8'));

const today = new Date().toISOString().slice(0, 10);

const urls = [
  { loc: `${SITE}/`, lastmod: today, priority: '1.0', changefreq: 'weekly' },
  { loc: `${SITE}/news/`, lastmod: today, priority: '0.8', changefreq: 'hourly' },
];
for (const p of pages) {
  urls.push({
    loc: `${SITE}/${p.slug}/`,
    lastmod: p.date.slice(0, 10),
    priority: '0.7',
    changefreq: 'yearly',
  });
}
for (const p of posts) {
  urls.push({
    loc: `${SITE}/${p.slug}/`,
    lastmod: p.date.slice(0, 10),
    priority: '0.6',
    changefreq: 'monthly',
  });
}

const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls.map((u) => `  <url>
    <loc>${u.loc}</loc>
    <lastmod>${u.lastmod}</lastmod>
    <changefreq>${u.changefreq}</changefreq>
    <priority>${u.priority}</priority>
  </url>`).join('\n')}
</urlset>
`;

fs.mkdirSync(DIST, { recursive: true });
fs.writeFileSync(path.join(DIST, 'sitemap.xml'), xml);

const robots = `User-agent: *
Allow: /

Sitemap: ${SITE}/sitemap.xml
`;
fs.writeFileSync(path.join(DIST, 'robots.txt'), robots);

console.log(`sitemap: ${urls.length} URLs → dist/sitemap.xml`);
