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

const hostname = "https://murugantemple.ca";
const appDir = path.join(process.cwd(), "src/app");

function getRoutesFromDirectory(dir = appDir, basePath = "") {
  let routes = [];
  const entries = fs.readdirSync(dir, { withFileTypes: true });

  for (let entry of entries) {
    if (entry.isDirectory()) {
      routes = routes.concat(
        getRoutesFromDirectory(path.join(dir, entry.name), `${basePath}/${entry.name}`)
      );
    } else if (entry.name.startsWith("page.")) {
      routes.push(basePath || "/");
    }
  }
  return routes;
}

function getBlogRoutes() {
  const filePath = path.join(process.cwd(), "utils/constant.utils.jsx");
  const content = fs.readFileSync(filePath, "utf-8");

  const blogPostsMatch = content.match(/blogPosts\s*=\s*\[([\s\S]*?)\]/);
  if (!blogPostsMatch) return [];

  const blogPostsContent = blogPostsMatch[1];


  const idRegex = /id\s*:\s*(\d+)/g;
  const slugs = [];
  let match;
  while ((match = idRegex.exec(blogPostsContent)) !== null) {
    slugs.push(`/blog/${match[1]}`);
  }

  return slugs;
}

(async function generateSitemap() {
  const sitemap = new SitemapStream({ hostname });

  const staticRoutes = getRoutesFromDirectory();
  const blogRoutes = getBlogRoutes();

  const allRoutes = [...new Set([...staticRoutes, ...blogRoutes])];

  allRoutes.forEach(route => {
    sitemap.write({
      url: route,
      changefreq: "weekly",
      priority: route === "/" ? 1.0 : 0.8
    });
  });

  sitemap.end();

  const sitemapData = await streamToPromise(sitemap);
  fs.writeFileSync(path.join(process.cwd(), "public", "sitemap.xml"), sitemapData.toString());

  console.log("✅ Sitemap generated successfully!");
})();
