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

const hostname = "https://rapharehab.ca";
const addTrailingSlash = true; // ✅ Set this true if your Next.js uses trailingSlash: true

// // 🔧 Utility to format URLs based on config
// const formatUrl = (url) => {
//   if (addTrailingSlash && !url.endsWith('/')) return url + '/';
//   if (!addTrailingSlash && url.endsWith('/') && url !== '/') return url.slice(0, -1);
//   return url;
// };
// Add a trailing slash only for “directory-like” URLs
const shouldAddSlash = (url) => {
  // keep "/" as is
  if (url === '/') return false;
  // don't touch file-like URLs (has extension)
  if (/\.[a-z0-9]{2,6}(\?.*)?$/i.test(url)) return false;
  return true;
};

const formatUrl = (url) => {
  // normalize to leading slash
  if (!url.startsWith('/')) url = '/' + url;

  if (addTrailingSlash && shouldAddSlash(url) && !url.endsWith('/')) {
    return url + '/';
  }
  if (!addTrailingSlash && url.endsWith('/') && url !== '/') {
    return url.slice(0, -1);
  }
  return url;
};

// ✅ Static pages
const staticLinks = [
  { url: '/', changefreq: 'daily', priority: 1.0 },
  { url: '/why-rapha-physiotherapy-etobicoke/', changefreq: 'weekly', priority: 0.7 },
  { url: '/faq-physiotherapy-etobicoke/', changefreq: 'weekly', priority: 0.7 },
  { url: '/what-to-expect/', changefreq: 'weekly', priority: 0.7 },
  { url: '/payment-insurance/', changefreq: 'weekly', priority: 0.7 }, 
  { url: '/locations/', changefreq: 'weekly', priority: 0.7 },
  { url: '/about-us/', changefreq: 'monthly', priority: 0.5 },
  { url: '/ourapproach-physiotherapy-etobicoke/', changefreq: 'monthly', priority: 0.5 },
  { url: '/our-team-physiotherapy-etobicoke/', changefreq: 'weekly', priority: 0.6 },
  { url: '/gallery-physiotherapy-etobicoke/', changefreq: 'weekly', priority: 0.6 },
  { url: '/covid-19-updates/', changefreq: 'weekly', priority: 0.6 },
  { url: '/etobicoke-treatment-service/', changefreq: 'weekly', priority: 0.6 },
  { url: '/area-of-injury/', changefreq: 'weekly', priority: 0.6 },
  { url: '/rehabilitation/', changefreq: 'weekly', priority: 0.6 },
  { url: '/accident/', changefreq: 'weekly', priority: 0.6 },
  { url: '/blog/', changefreq: 'weekly', priority: 0.6 },
  { url: '/contact/', changefreq: 'weekly', priority: 0.6 },
  { url: '/caregivers/', changefreq: 'weekly', priority: 0.6 },
  { url: '/shortcodes/', changefreq: 'weekly', priority: 0.6 },
];

// ✅ Dynamic blog posts
const blogPosts = [
  { slug: '/blog/chronic-pain-treatment-etobicoke/' },
  { slug: '/blog/top-rehab-wellness-etobicoke-hand-massage/' },
  { slug: '/blog/osteopath-near-me-first-visit-rapha-rehab/' },
  { slug: '/blog/strength-training-rehabilitation-rapha-rehab/' },
  { slug: '/blog/biceps-triceps-back-workouts-rapha-rehab/' },
  { slug: '/blog/beginner-workouts-rehab-wellness-rapha-rehab/' },
  { slug: '/blog/recover-strong-post-surgery-rehabilitation-exercises/' },
  { slug: '/blog/benefits-massage-therapy-sports-injuries/' },
  { slug: '/blog/shockwave-therapy-etobicoke-chronic-pain/' },
  { slug: '/blog/what-sets-rapharehab-apart-from-Other-physiotherapy-clinics/' },
  { slug: '/blog/how-long-are-the-rapha-rehab-physiotherapy-sessions-what-you-should-know/' },
];

// Convert blog slugs to sitemap entries
const blogLinks = blogPosts.map(post => ({
  url: `${post.slug}`,
  changefreq: 'weekly',
  priority: 0.6
}));



// ✅ Dynamic Services
const services = [
  { slug: '/etobicoke-treatment-service/physiotherapy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/sportsinjury-physiotherapy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/pelvic-floor-physiotherapy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/massage-therapy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/chiropractic-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/chiropdist-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/acupuncture-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/osteopathy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/foot-reflexology-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/custom-knee-braces-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/laser-therapy-electrical-modalities/' },
  { slug: '/etobicoke-treatment-service/naturopathy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/orthotics-etobicoke/' },
  { slug: '/etobicoke-treatment-service/spinal-decompression-therapy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/concussion-management-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/chronic-pain-management-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/pre-post-operative-management-etobicoke/' },
  { slug: '/etobicoke-treatment-service/exercisetherapy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/workplace-injury-management-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/home-care-physiotherapy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/virtual-care-physiotherapy-clinic-etobicoke/' },
  { slug: '/etobicoke-treatment-service/gait-assessment-etobicoke/' },
  { slug: '/etobicoke-treatment-service/kids-physiotherapy-etobicoke/' },
  { slug: '/etobicoke-treatment-service/surgical-rehab-etobicoke/' },
  { slug: '/etobicoke-treatment-service/fascial-stretch-therapy-etobicoke/' },
  { slug: '/etobicoke-treatment-service/cupping-therapy-etobicoke/' },
  { slug: '/etobicoke-treatment-service/shiatsu-therapy-etobicoke/' },
  { slug: '/etobicoke-treatment-service/deep-tissue-massage-etobicoke/' },
  { slug: '/etobicoke-treatment-service/neuro-fascial-therapy-etobicoke/' },
  { slug: '/etobicoke-treatment-service/cranio-sacral-therapy-etobicoke/' },
  { slug: '/etobicoke-treatment-service/motor-vehicle-accident-rehabilitation-etobicoke/' },
  { slug: '/etobicoke-treatment-service/compression-stockings-etobicoke/' },
  { slug: '/etobicoke-treatment-service/cardiac-rehabilitation-etobicoke/' },
  { slug: '/etobicoke-treatment-service/intramuscular-stimulation-ims-etobicoke/' },
  { slug: '/etobicoke-treatment-service/psychotherapy-etobicoke/' },
  { slug: '/etobicoke-treatment-service/shockwave-therapy-etobicoke/' },
];

// Convert services slugs to sitemap entries
const servicesLinks = services.map(post => ({
  url: `${post.slug}`,
  changefreq: 'weekly',
  priority: 0.6
}));


// ✅ Dynamic area-of-injury
const areas = [
  { slug: '/area-of-injury/head-injury-physiotherapy-management-etobicoke/' },
  { slug: '/area-of-injury/neck-injury-physiotherapy-management-etobicoke/' },
  { slug: '/area-of-injury/shoulder-injury-physiotherapy-management-etobicoke/' },
  { slug: '/area-of-injury/elbow-injury-physiotherapy-management-etobicoke/' },
  { slug: '/area-of-injury/wristhand-injury-physiotherapy-management-etobicoke/' },
  { slug: '/area-of-injury/lowback-injury-physiotherapy-management-etobicoke/' },
  { slug: '/area-of-injury/hip-injury-physiotherapy-management-etobicoke/' },
  { slug: '/area-of-injury/legknee-injury-physiotherapy-management-etobicoke/' },
  { slug: '/area-of-injury/anklefoot-injury-physiotherapy-management-etobicoke/' },
];

// Convert Areas of Injury slugs to sitemap entries
const areasLinks = areas.map(post => ({
  url: `${post.slug}`,
  changefreq: 'weekly',
  priority: 0.6
}));


// ✅ Dynamic Rehabilitation
const rehabilitation = [
  { slug: '/rehabilitation/spinalcord-rehabilitation-clinic-etobicoke/' },
  { slug: '/rehabilitation/amputee-rehabilitation-clinic-etobicoke/' },
  { slug: '/rehabilitation/fracture-rehabilitation-clinic-etobicoke/' },
  { slug: '/rehabilitation/neurological-rehabilitation-clinic-etobicoke/' },
];

// Convert Areas of Injury slugs to sitemap entries
const rehabilitationLinks = rehabilitation.map(post => ({
  url: `${post.slug}`,
  changefreq: 'weekly',
  priority: 0.6
}));


// ✅ Dynamic Accident
const accident = [
  { slug: '/accident/minor-injury-etobicoke/' },
  { slug: '/accident/catastropic-injury-etobicoke/' },
  { slug: '/accident/slip-and-fall-injury-etobicoke/' },
  { slug: '/accident/concussion-management-etobicoke/' },
  { slug: '/accident/psychotherapy-management-etobicoke/' },
  { slug: '/accident/hydrotherapy-etobicoke/' },
  { slug: '/accident/chronic-pain-management-etobicoke/' },
];

// Convert Accident slugs to sitemap entries
const accidentLinks = accident.map(post => ({
  url: `${post.slug}`,
  changefreq: 'weekly',
  priority: 0.6
}));


// ✅ Dynamic Our Team
const ourteam = [
  { slug: '/our-team-physiotherapy-etobicoke/dhanya-prashant/' },
  { slug: '/our-team-physiotherapy-etobicoke/chandra-babu/' },
  { slug: '/our-team-physiotherapy-etobicoke/jo-anne/' },
];

// Convert Our Team slugs to sitemap entries
const ourteamLinks = ourteam.map(post => ({
  url: `${post.slug}`,
  changefreq: 'weekly',
  priority: 0.6
}));

const allLinks = [...staticLinks, ...blogLinks, ...servicesLinks, ...areasLinks, ...rehabilitationLinks, ...accidentLinks, ...ourteamLinks].map(link => ({
  ...link,
  url: formatUrl(link.url),
}));

async function generateSitemap() {
  try {
    const sitemap = new SitemapStream({ hostname: 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();
