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

const hostname = "https://rapharehap.metatronnest.com"; 
const appDir = path.join(process.cwd(), "app");
const outputPath = path.join(process.cwd(), "public", "sitemap.xml");

function getRoutesFromApp(dir = appDir, basePath = "") {
  let routes = [];
  if (!fs.existsSync(dir)) return routes;

  const entries = fs.readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    if (entry.name.startsWith("_") || entry.name === "api" || entry.name.startsWith(".")) continue;
    const fullPath = path.join(dir, entry.name);

    if (entry.isDirectory()) {
      if (!entry.name.startsWith("[")) {
        const hasPage =
          fs.existsSync(path.join(fullPath, "page.js")) ||
          fs.existsSync(path.join(fullPath, "page.jsx")) ||
          fs.existsSync(path.join(fullPath, "index.js")) ||
          fs.existsSync(path.join(fullPath, "index.jsx"));
        if (hasPage) {
          const cleaned = path.join(basePath, entry.name).replace(/\\/g, "/");
          routes.push(`/${cleaned}/`);
        }
      }
      routes = routes.concat(getRoutesFromApp(fullPath, path.join(basePath, entry.name)));
    } else if (entry.isFile()) {
      if (["page.js", "page.jsx", "index.js", "index.jsx"].includes(entry.name)) {
        const cleaned = basePath.replace(/\\/g, "/");
        const route = "/" + (cleaned ? `${cleaned}/` : "");
        routes.push(route);
      }
    }
  }

  return [...new Set(routes.map(r => r.replace(/\/{2,}/g, "/")))];
}

async function loadESModule(relativePath) {
  const fullPath = path.join(process.cwd(), relativePath);
  if (!fs.existsSync(fullPath)) return null;
  const mod = await import(pathToFileURL(fullPath).href);
  return mod.default ?? mod.Blogs ?? [];
}

async function generateSitemap() {
  try {
  
    const staticRoutes = getRoutesFromApp();
    const staticLinks = staticRoutes.map(route => ({
      url: route,
      changefreq: "weekly",
      priority: route === "/" ? 1.0 : 0.8,
    }));

    const Blogs = await loadESModule("utils/Blog.utils.js");
    const blogLinks = (Blogs || []).map(post => ({
      url: `/blog/${post.slug}/`,
      changefreq: "weekly",
      priority: 0.8,
    }));

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

    const sitemap = new SitemapStream({ hostname });
    const writeStream = fs.createWriteStream(outputPath);
    sitemap.pipe(writeStream);

    allLinks.forEach(link => {
      sitemap.write(link);
      console.log("✅ writing:", link.url);
    });

    sitemap.end();
    await streamToPromise(sitemap);

    console.log(`🎉 sitemap.xml generated at ${outputPath} (${allLinks.length} URLs)`);
  } catch (err) {
    console.error("❌ Failed to generate sitemap:", err);
    process.exit(1);
  }
}

generateSitemap();
