const fs = require('fs');
const path = require('path');
const { SitemapStream, streamToPromise } = require('sitemap');

const APP_DIR = path.join(__dirname, '../app');

function getAppRoutes(dir = APP_DIR, baseRoute = '') {
  let routes = [];

  const items = fs.readdirSync(dir);
  items.forEach((item) => {
    const itemPath = path.join(dir, item);
    const stat = fs.statSync(itemPath);

    if (stat.isDirectory()) {
      const newBase = baseRoute + '/' + item;
      routes = routes.concat(getAppRoutes(itemPath, newBase));
    } else if (item === 'page.tsx' || item === 'page.js') {
      routes.push(baseRoute || '/');
    }
  });

  return routes;
}

const staticPaths = getAppRoutes().map((url) =>
  url.endsWith('/') && url !== '/' ? url.slice(0, -1) : url
);

const staticLinks = staticPaths.map((url) => ({
  url,
  changefreq: 'weekly',
  priority: 0.8,
}));

// Example dynamic slugs
const tamilCulturePosts = [
  { slug: 'instrumental-music' },
  { slug: 'bharathnatyam-dance' },
  { slug: 'vocal' },
];

const cultureLinks = tamilCulturePosts.map((post) => ({
  url: `/tamil-culture-post/?slug=${post.slug}`,
  changefreq: 'weekly',
  priority: 0.64,
}));

const allLinks = [...staticLinks, ...cultureLinks];

async function generateSitemap() {
  try {
    const sitemap = new SitemapStream({
      hostname: 'https://tca.metatronnest.com',
    });

    const outputPath = path.resolve(__dirname, '../public/sitemap.xml');
    const writeStream = fs.createWriteStream(outputPath);

    sitemap.pipe(writeStream);

    allLinks.forEach((link) => sitemap.write(link));
    sitemap.end();

    await streamToPromise(sitemap);

    console.log(`✅ sitemap.xml created with ${allLinks.length} URLs!`);
  } catch (err) {
    console.error('❌ Error generating sitemap:', err);
  }
}

generateSitemap();
