// scripts/generate-sitemap.js
const fs = require("fs");
const path = require("path");
const { SitemapStream, streamToPromise } = require("sitemap");

const hostname = "https://sixty5street.com";
const addTrailingSlash = true;

// Utility to determine if a trailing slash should be added
const shouldAddSlash = (url) => {
  if (url === "/") return false;
  if (/\.[a-z0-9]{2,6}(\?.*)?$/i.test(url)) return false; // skip files
  return true;
};

// Format URL to ensure proper slashes and handle anchors
const formatUrl = (url) => {
  // Split path and hash
  let [pathPart, hashPart] = url.split("#");

  // Remove extra leading slashes and ensure single starting slash
  pathPart = "/" + pathPart.replace(/^\/+/, "");

  // Add or remove trailing slash for pathPart
  if (addTrailingSlash && shouldAddSlash(pathPart) && !pathPart.endsWith("/")) {
    pathPart += "/";
  }
  if (!addTrailingSlash && pathPart.endsWith("/") && pathPart !== "/") {
    pathPart = pathPart.slice(0, -1);
  }

  // Recombine with hash if it exists
  return hashPart ? pathPart + "#" + hashPart : pathPart;
};

// List of URLs to include in sitemap
const sectionLinks = [
  { url: "/", changefreq: "daily", priority: 1.0 },
  { url: "/about", changefreq: "weekly", priority: 0.8 },
  { url: "/gallery", changefreq: "monthly", priority: 0.7 },
  { url: "/menu", changefreq: "weekly", priority: 0.8 },
  { url: "/blog", changefreq: "weekly", priority: 0.7 },
  { url: "/contact", changefreq: "weekly", priority: 0.7 },
];

const blogPosts = [
  {
    slug: "/blog/how-sixty5-streets-fusion-of-shawarma-wings-and-dosa-is-changing-indian-street-food-in-the-gta/",
  },
  {
    slug: "/blog/from-dosa-to-biryani-5-must-try-menu-items-at-sixty5-street-for-your-next-takeout/",
  },
  {
    slug: "/blog/behind-the-counter-the-story-of-sixty5-streets-fast-casual-kitchen-and-why-it-works-in-ontario/",
  },
  {
    slug: "/blog/what-type-of-street-food-does-sixty5-street-serve-in-brampton/",
  },
  {
    slug: "/blog/what-are-sixty5-street-most-popular-dishes/",
  },
  {
    slug: "/blog/how-does-sixty5-street-brampton-make-its-dosas-and-wraps-so-crispy-and-flavorful/",
  },
  {
    slug: "/blog/how-does-sixty5-street-create-the-best-balance-of-unique-flavors-in-every-wrap/",
  },
  {
    slug: "/blog/what-are-the-sixty5-street-specials-a-complete-guide-to-the-menu-items-you-need-to-try/",
  },
  {
    slug: "/blog/why-do-foodies-call-sixty5-street-the-best-place-to-try-unique-indian-street-food-in-the-gta/",
  },
  {
    slug: "/blog/what-makes-sixty5-streets-food-unique-compared-to-other-fast-casual-restaurants/",
  },
  {
    slug: "/blog/how-are-sixty5-streets-wings-prepared-and-what-sauces-flavours-are-offered/",
  },
  {
    slug: "/blog/what-are-the-best-street-food-drinks-to-pair-with-sixty5-streets-menu-items/",
  },
  {
    slug: "/blog/what-are-the-most-underrated-items-on-the-sixty5-street-menu-that-deserve-more-attention/",
  },
  {
    slug: "/blog/what-makes-sixty5-streets-wraps-different-from-other-local-wrap-shops-in-brampton-and-the-gta/",
  },
  {
    slug: "/blog/what-are-the-best-late-night-orders-at-sixty5-street/",
  },
  {
    slug: "/blog/how-sixty5-street-supports-local-events-and-community-food-initiatives-in-brampton/",
  },
  {
    slug: "/blog/why-sixty5-street-is-one-of-the-best-casual-eats-in-brampton/",
  }

];

// Format all URLs
const blogLinks = blogPosts.map((post) => ({
  url: formatUrl(post.slug),
  changefreq: "weekly",
  priority: 0.6,
}));

const allLinks = [...sectionLinks, ...blogLinks].map((link) => ({
  ...link,
  url: formatUrl(link.url),
}));

// Generate sitemap.xml
async function generateSitemap() {
  try {
    const sitemap = new SitemapStream({ hostname });
    const writeStream = fs.createWriteStream(
      path.resolve(__dirname, "../public/sitemap.xml")
    );

    sitemap.pipe(writeStream);

    console.log("📦 Writing URLs to sitemap:");
    allLinks.forEach((link) => {
      console.log(" -", hostname + link.url);
      sitemap.write(link);
    });

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

    console.log("✅ sitemap.xml created successfully!");
  } catch (error) {
    console.error("❌ Error creating sitemap.xml:", error);
  }
}

generateSitemap();