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

const hostname = "https://socialbuddy-marketing.metatronnest.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: "/pricing", changefreq: "weekly", priority: 0.8 },
    { url: "/contact", changefreq: "weekly", priority: 0.7 },
    { url: "/careers", changefreq: "weekly", priority: 0.7 },
    { url: "/resources", changefreq: "weekly", priority: 0.7 },
];

// Features pages
const featureLinks = [
    { url: "/features/publish", changefreq: "weekly", priority: 0.7 },
    { url: "/features/analyze", changefreq: "weekly", priority: 0.7 },
    { url: "/features/engage", changefreq: "weekly", priority: 0.7 },
    { url: "/features/create", changefreq: "weekly", priority: 0.7 },
    { url: "/features/start-page", changefreq: "weekly", priority: 0.7 },
    { url: "/features/ai-assistant", changefreq: "weekly", priority: 0.7 },
];

// Channel pages
const channelLinks = [
    { url: "/channels/instagram", changefreq: "weekly", priority: 0.7 },
    { url: "/channels/facebook", changefreq: "weekly", priority: 0.7 },
    { url: "/channels/twitter", changefreq: "weekly", priority: 0.7 },
    { url: "/channels/linkedin", changefreq: "weekly", priority: 0.7 },
    { url: "/channels/tiktok", changefreq: "weekly", priority: 0.7 },
    { url: "/channels/pinterest", changefreq: "weekly", priority: 0.7 },

];

// Resources pages
const resourceLinks = [
    { url: "/resources/mastering-social-media-scheduling", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/best-times-to-post-instagram", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/content-calendar-templates", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/understanding-social-metrics", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/roi-social-media-marketing", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/creating-custom-reports", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/community-management-best-practices", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/managing-negative-comments", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/social-listening-guide", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/design-tips-non-designers", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/video-content-trends", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/writing-engaging-captions", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/optimizing-link-in-bio", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/landing-page-conversion", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/personal-branding-tips", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/ai-for-content-creation", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/future-of-marketing-ai", changefreq: "weekly", priority: 0.6 },
    { url: "/resources/humanizing-ai-content", changefreq: "weekly", priority: 0.6 },
];

// Format all URLs
const allLinks = [
    ...sectionLinks,
    ...featureLinks,
    ...channelLinks,
    ...resourceLinks,
].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();
