remove the errors and rewrite the code
/**
 * Sitemap URL Fetcher and Metadata Extractor
 * Fetches URLs from sitemap and extracts metadata
 * Author: Generated by AI Assistant
 * Version: 1.0
 */

// Configuration
const CONFIG = {
  MAX_URLS: 800,
  BATCH_SIZE: 20,
  DELAY_BETWEEN_BATCHES: 1000, // milliseconds
  DELAY_BETWEEN_REQUESTS: 100, // milliseconds
  TIMEOUT: 10000 // 10 seconds
};

/**
 * Main function to start the process
 */
function main() {
  try {
    // Get sitemap URL from user
    const sitemapUrl = Browser.inputBox(
      'Sitemap URL Input',
      'Please enter the sitemap URL:',
      Browser.Buttons.OK_CANCEL
    );
    
    if (sitemapUrl === 'cancel' || !sitemapUrl) {
      Browser.msgBox('Process cancelled by user.');
      return;
    }
    
    // Validate URL
    if (!isValidUrl(sitemapUrl)) {
      Browser.msgBox('Invalid URL provided. Please enter a valid sitemap URL.');
      return;
    }
    
    Browser.msgBox('Starting sitemap processing. This may take several minutes...');
    
    // Fetch URLs from sitemap
    const urls = fetchSitemapUrls(sitemapUrl);
    
    if (urls.length === 0) {
      Browser.msgBox('No URLs found in the sitemap.');
      return;
    }
    
    // Create or clear sheets
    const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    const urlSheet = createOrClearSheet(spreadsheet, 'URLs');
    const metadataSheet = createOrClearSheet(spreadsheet, 'Metadata');
    
    // Setup URL sheet
    setupUrlSheet(urlSheet, urls);
    
    // Setup metadata sheet
    setupMetadataSheet(metadataSheet);
    
    // Process URLs for metadata
    processUrlsForMetadata(urls, metadataSheet);
    
    Browser.msgBox(`Process completed! Found ${urls.length} URLs and extracted metadata.`);
    
  } catch (error) {
    console.error('Error in main function:', error);
    Browser.msgBox('An error occurred: ' + error.toString());
  }
}

/**
 * Validate URL format
 */
function isValidUrl(string) {
  try {
    new URL(string);
    return true;
  } catch (_) {
    return false;
  }
}

/**
 * Fetch URLs from sitemap
 */
function fetchSitemapUrls(sitemapUrl) {
  try {
    console.log('Fetching sitemap from:', sitemapUrl);
    
    const response = UrlFetchApp.fetch(sitemapUrl, {
      method: 'GET',
      followRedirects: true,
      muteHttpExceptions: true,
      headers: {
        'User-Agent': 'Mozilla/5.0 (compatible; Google Apps Script)'
      }
    });
    
    if (response.getResponseCode() !== 200) {
      throw new Error(`Failed to fetch sitemap. Status: ${response.getResponseCode()}`);
    }
    
    const xmlContent = response.getContentText();
    const urls = [];
    
    // Parse XML to extract URLs
    if (xmlContent.includes('')) {
      // Handle sitemap index
      const sitemapMatches = xmlContent.match(/(.*?)<\/loc>/g);
      if (sitemapMatches) {
        for (const match of sitemapMatches.slice(0, 10)) { // Limit to 10 sitemaps
          const sitemapUrl = match.replace(/<\/?loc>/g, '').trim();
          const subUrls = fetchSitemapUrls(sitemapUrl);
          urls.push(...subUrls);
          if (urls.length >= CONFIG.MAX_URLS) break;
        }
      }
    } else {
      // Handle regular sitemap
      const urlMatches = xmlContent.match(/(.*?)<\/loc>/g);
      if (urlMatches) {
        for (const match of urlMatches) {
          const url = match.replace(/<\/?loc>/g, '').trim();
          if (url && isValidUrl(url)) {
            urls.push(url);
          }
          if (urls.length >= CONFIG.MAX_URLS) break;
        }
      }
    }
    
    console.log(`Found ${urls.length} URLs in sitemap`);
    return urls.slice(0, CONFIG.MAX_URLS);
    
  } catch (error) {
    console.error('Error fetching sitemap:', error);
    throw new Error('Failed to fetch sitemap: ' + error.toString());
  }
}

/**
 * Create or clear sheet
 */
function createOrClearSheet(spreadsheet, sheetName) {
  let sheet = spreadsheet.getSheetByName(sheetName);
  
  if (sheet) {
    sheet.clear();
  } else {
    sheet = spreadsheet.insertSheet(sheetName);
  }
  
  return sheet;
}

/**
 * Setup URL sheet with formatting
 */
function setupUrlSheet(sheet, urls) {
  // Set headers
  const headers = ['Sr.No', 'URL'];
  sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
  
  // Format header row
  const headerRange = sheet.getRange(1, 1, 1, headers.length);
  headerRange.setBackground('#4a90e2'); // Dark cornflower blue
  headerRange.setFontColor('#ffffff'); // White text
  headerRange.setFontWeight('bold');
  headerRange.setHorizontalAlignment('center');
  
  // Add URLs with serial numbers
  const data = urls.map((url, index) => [index + 1, url]);
  
  if (data.length > 0) {
    sheet.getRange(2, 1, data.length, 2).setValues(data);
  }
  
  // Auto-resize columns
  sheet.autoResizeColumns(1, headers.length);
  
  // Freeze header row
  sheet.setFrozenRows(1);
}

/**
 * Setup metadata sheet with formatting
 */
function setupMetadataSheet(sheet) {
  // Set headers
  const headers = ['Sr.No', 'URL', 'Meta Title', 'Meta Description', 'H1 Heading'];
  sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
  
  // Format header row
  const headerRange = sheet.getRange(1, 1, 1, headers.length);
  headerRange.setBackground('#4a90e2'); // Dark cornflower blue
  headerRange.setFontColor('#ffffff'); // White text
  headerRange.setFontWeight('bold');
  headerRange.setHorizontalAlignment('center');
  
  // Auto-resize columns
  sheet.autoResizeColumns(1, headers.length);
  
  // Freeze header row
  sheet.setFrozenRows(1);
}

/**
 * Process URLs for metadata extraction
 */
function processUrlsForMetadata(urls, sheet) {
  const totalUrls = urls.length;
  const batches = Math.ceil(totalUrls / CONFIG.BATCH_SIZE);
  
  console.log(`Processing ${totalUrls} URLs in ${batches} batches`);
  
  for (let batchIndex = 0; batchIndex < batches; batchIndex++) {
    const startIndex = batchIndex * CONFIG.BATCH_SIZE;
    const endIndex = Math.min(startIndex + CONFIG.BATCH_SIZE, totalUrls);
    const batchUrls = urls.slice(startIndex, endIndex);
    
    console.log(`Processing batch ${batchIndex + 1}/${batches} (URLs ${startIndex + 1}-${endIndex})`);
    
    // Process each URL in the batch
    const batchData = [];
    
    for (let i = 0; i < batchUrls.length; i++) {
      const url = batchUrls[i];
      const urlIndex = startIndex + i;
      
      try {
        const metadata = extractMetadata(url);
        batchData.push([
          urlIndex + 1, // Sr.No
          url,
          metadata.title || 'N/A',
          metadata.description || 'N/A',
          metadata.h1 || 'N/A'
        ]);
        
        // Small delay between requests
        if (i < batchUrls.length - 1) {
          Utilities.sleep(CONFIG.DELAY_BETWEEN_REQUESTS);
        }
        
      } catch (error) {
        console.error(`Error processing URL ${url}:`, error);
        batchData.push([
          urlIndex + 1,
          url,
          'ERROR',
          'Failed to fetch',
          'ERROR'
        ]);
      }
    }
    
    // Write batch data to sheet
    if (batchData.length > 0) {
      const startRow = startIndex + 2; // +2 because row 1 is header and we start from row 2
      sheet.getRange(startRow, 1, batchData.length, 5).setValues(batchData);
    }
    
    // Delay between batches (except for the last batch)
    if (batchIndex < batches - 1) {
      Utilities.sleep(CONFIG.DELAY_BETWEEN_BATCHES);
    }
  }
}

/**
 * Extract metadata from a URL
 */
function extractMetadata(url) {
  try {
    const response = UrlFetchApp.fetch(url, {
      method: 'GET',
      followRedirects: true,
      muteHttpExceptions: true,
      headers: {
        'User-Agent': 'Mozilla/5.0 (compatible; Google Apps Script)'
      }
    });
    
    if (response.getResponseCode() !== 200) {
      throw new Error(`HTTP ${response.getResponseCode()}`);
    }
    
    const html = response.getContentText();
    
    // Extract meta title
    let title = '';
    const titleMatch = html.match(/]*>(.*?)<\/title>/is);
    if (titleMatch) {
      title = titleMatch[1].replace(/\s+/g, ' ').trim();
    }
    
    // Extract meta description
    let description = '';
    const descMatch = html.match(/]*name=["\']description["\'][^>]*content=["\']([^"\']*)["\'][^>]*>/i);
    if (descMatch) {
      description = descMatch[1].replace(/\s+/g, ' ').trim();
    }
    
    // Extract H1 heading
    let h1 = '';
    const h1Match = html.match(/]*>(.*?)<\/h1>/is);
    if (h1Match) {
      h1 = h1Match[1].replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
    }
    
    return {
      title: title,
      description: description,
      h1: h1
    };
    
  } catch (error) {
    console.error(`Error extracting metadata from ${url}:`, error);
    throw error;
  }
}

/**
 * Utility function to clean up HTML entities
 */
function cleanHtmlEntities(text) {
  return text
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"')
    .replace(/'/g, "'")
    .replace(/ /g, ' ')
    .trim();
}

/**
 * Test function for development
 */
function testFunction() {
  // Test with a sample sitemap URL
  const testUrl = 'https://example.com/sitemap.xml';
  console.log('Testing with URL:', testUrl);
  
  try {
    const urls = fetchSitemapUrls(testUrl);
    console.log('Found URLs:', urls.length);
    
    if (urls.length > 0) {
      const metadata = extractMetadata(urls[0]);
      console.log('Sample metadata:', metadata);
    }
  } catch (error) {
    console.error('Test error:', error);
  }
}