/**
 * Environment-aware URL setup script
 * Updates sitemap.xml and index.html with the correct URLs based on VITE_APP_SITE_URL
 * 
 * Usage: node scripts/setup-env-urls.js
 * 
 * Environment variables:
 * - VITE_APP_SITE_URL: The full site URL (e.g., https://lotr-prod.testingfantasy.com)
 *   If not set, defaults to http://localhost:5173 for development
 */

const fs = require('fs');
const path = require('path');

// Get the site URL from environment variable or use default for development
const siteUrl = process.env.VITE_APP_SITE_URL || 'http://localhost:5173';

console.log(`🌍 Setting up environment-aware URLs with: ${siteUrl}`);

// Update sitemap.xml
const sitemapPath = path.join(__dirname, '../public/sitemap.xml');
try {
  let sitemapContent = fs.readFileSync(sitemapPath, 'utf-8');
  const originalSitemap = sitemapContent;
  
  // Replace all occurrences of the placeholder
  sitemapContent = sitemapContent.replace(/%VITE_APP_SITE_URL%/g, siteUrl);
  
  if (originalSitemap !== sitemapContent) {
    fs.writeFileSync(sitemapPath, sitemapContent, 'utf-8');
    console.log(`✅ Updated sitemap.xml with environment-aware URLs`);
  } else {
    console.log(`ℹ️  sitemap.xml already has correct URLs`);
  }
} catch (error) {
  console.error(`❌ Error updating sitemap.xml:`, error.message);
  process.exit(1);
}

// Update index.html
const indexPath = path.join(__dirname, '../public/index.html');
try {
  let indexContent = fs.readFileSync(indexPath, 'utf-8');
  const originalIndex = indexContent;
  
  // Replace all occurrences of the placeholder
  indexContent = indexContent.replace(/%VITE_APP_SITE_URL%/g, siteUrl);
  
  if (originalIndex !== indexContent) {
    fs.writeFileSync(indexPath, indexContent, 'utf-8');
    console.log(`✅ Updated index.html with environment-aware URLs`);
  } else {
    console.log(`ℹ️  index.html already has correct URLs`);
  }
} catch (error) {
  console.error(`❌ Error updating index.html:`, error.message);
  process.exit(1);
}

console.log(`\n✨ Environment setup complete!`);
console.log(`📍 Site URL: ${siteUrl}`);
