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-choose-us/', changefreq: 'weekly', priority: 0.7 },
  { url: '/faq/', 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: '/our-approach-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: '/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/' },
  { slug: '/blog/post-surgery-rehabilitation-in-etobicoke-step-by-step-guide-to-faster-recovery/' },
  { slug: '/blog/top-benefits-of-physiotherapy-in-etobicoke-for-pain-relief-and-better-mobility/' },
  { slug: '/blog/sports-injury-rehabilitation-how-etobicoke-athletes-recover-faster-with-rapharehab/' },
  { slug: '/blog/what-is-the-best-treatment-for-chronic-back-pain-in-etobicoke-and-how-long-does-recovery-take/' },
  { slug: '/blog/can-massage-therapy-at-rapha-rehab-help-with-sports-injuries-or-muscle-stiffness/' },
  { slug: '/blog/pelvic-floor-physiotherapy-in-etobicoke/' },
  { slug: '/blog/is-massage-therapy-good-for-sports-injuries-or-muscle-stiffness-in-etobicoke/' },
  { slug: '/blog/why-is-rapha-rehab-known-for-the-best-osteopathy-treatments-in-etobicoke/' },
  { slug: '/blog/what-makes-rapha-rehabs-massage-therapy-among-the-best-in-etobicoke/' },
  { slug: '/blog/why-choose-rapha-rehab-for-the-best-custom-orthotics-in-etobicoke/' },
  { slug: '/blog/what-makes-rapha-rehab-offer-the-best-acupuncture-in-etobicoke/' },
  { slug: '/blog/what-makes-rapha-rehab-massage-therapy-in-etobicoke-so-special/' },
  { slug: '/blog/how-rapha-rehab-delivers-the-best-long-term-pain-management-in-etobicoke/' },
  { slug: '/blog/why-is-rapha-rehab-known-for-the-best-sports-injury-treatments/' },
  { slug: '/blog/what-makes-rapha-rehab-offer-the-best-pelvic-floor-physiotherapy/' },
  { slug: '/blog/why-rapha-rehab-is-the-first-choice-for-runners-injury-treatment-in-etobicoke/' },
  { slug: '/blog/gym-injury-rehabilitation-in-etobicoke-why-athletes-trust-rapha-rehab/' },
  { slug: '/blog/how-rapha-rehab-helps-busy-professionals-recover-from-sports-injuries-in-etobicoke/' },
  { slug: '/blog/preventing-sports-injuries-in-etobicoke-expert-tips-from-rapha-rehab/' },
  { slug: '/blog/what-makes-rapha-rehab-offer-the-best-spinal-decompression-therapy/' },
  { slug: '/blog/why-is-rapha-rehab-a-top-provider-of-the-best-home-physiotherapy-care/' },
  { slug: '/blog/concussion-care-physiotherapy-etobicoke-why-rapha-rehab-is-top-local-choice/' },
  { slug: '/blog/post-surgery-recovery-care-etobicoke-why-rapha-rehab-feels-different/' },
  { slug: '/blog/how-our-etobicoke-clinic-really-delivers-great-therapeutic-massage/' },
  { slug: '/blog/what-benefits-come-from-choosing-the-best-osteopathic-care-at-rapha-rehab/' },
  { slug: '/blog/massage-therapy-clinic-in-etobicoke-rapha-rehab/' },
  { slug: '/blog/acupuncture-clinic-in-etobicoke-rapha-rehab/' },
];

// 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/osteopathy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/massage-therapy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/acupuncture-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/chiropodist-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/chiropractic-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/orthotics-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/foot-reflexology-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/custom-knee-braces-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/laser-therapy-electrical-modalities-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/virtual-care-physiotherapy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/naturopathy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/spinal-decompression-therapy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/concussion-management-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/chronic-pain-management-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/prepost-operative-management-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/exercisetherapy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/workplace-injury-management-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/pelvic-floor-physiotherapy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/home-care-physiotherapy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/sportsinjury-physiotherapy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/gait-assessment-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/kids-physiotherapy-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/surgical-rehab-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/physiotherapy-clinic-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/fascial-stretch-therapy-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/cupping-therapy-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/shiatsu-therapy-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/deep-tissue-massage-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/neuro-fascial-therapy-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/cranio-sacral-therapy-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/motor-vehicle-accident-rehabilitation-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/compression-stockings-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/cardiac-rehabilitation-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/intramuscular-stimulation-ims-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/psychotherapy-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/shockwave-therapy-in-etobicoke/' },
  { slug: '/etobicoke-treatment-service/refugee-physiotherapy-in-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-in-etobicoke/' },
  { slug: '/area-of-injury/neck-injury-physiotherapy-management-in-etobicoke/' },
  { slug: '/area-of-injury/shoulder-injury-physiotherapy-management-in-etobicoke/' },
  { slug: '/area-of-injury/elbow-injury-physiotherapy-management-in-etobicoke/' },
  { slug: '/area-of-injury/wristhand-injury-physiotherapy-management-in-etobicoke/' },
  { slug: '/area-of-injury/lowback-injury-physiotherapy-management-in-etobicoke/' },
  { slug: '/area-of-injury/hip-injury-physiotherapy-management-in-etobicoke/' },
  { slug: '/area-of-injury/legknee-injury-physiotherapy-management-in-etobicoke/' },
  { slug: '/area-of-injury/anklefoot-injury-physiotherapy-management-in-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-in-etobicoke/' },
  { slug: '/rehabilitation/amputee-rehabilitation-clinic-in-etobicoke/' },
  { slug: '/rehabilitation/fracture-rehabilitation-clinic-in-etobicoke/' },
  { slug: '/rehabilitation/neurological-rehabilitation-clinic-in-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-care-in-etobicoke/' },
  { slug: '/accident/catastrophic-injury-in-etobicoke/' },
  { slug: '/accident/slip-and-fall-injury-in-etobicoke/' },
  { slug: '/accident/concussion-management-in-etobicoke/' },
  { slug: '/accident/psychotherapy-management-in-etobicoke/' },
  { slug: '/accident/hydrotherapy-in-etobicoke/' },
  { slug: '/accident/chronic-pain-management-in-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();
