#!/usr/bin/env node

import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import { glob } from 'glob';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, '..');

// Regex to match JSON imports that have the assert { type: 'json' }
const jsonImportWithAssertRegex = /^(import\s+.+?\s+from\s+['"].*?\.json['"])\s+assert\s+\{\s*type\s*:\s*['"]json['"]\s*\}\s*;/gm;

async function processFile(filePath) {
  try {
    // Read the file content
    const content = await fs.readFile(filePath, 'utf8');
    
    // Check if the file contains JSON imports with assertions
    if (!jsonImportWithAssertRegex.test(content)) {
      return false; // No changes needed
    }
    
    // Reset regex lastIndex
    jsonImportWithAssertRegex.lastIndex = 0;
    
    // Replace the assertions in JSON imports
    const updatedContent = content.replace(jsonImportWithAssertRegex, '$1;');
    
    // Write the updated content back to the file
    await fs.writeFile(filePath, updatedContent, 'utf8');
    
    return true; // File was updated
  } catch (error) {
    console.error(`Error processing file ${filePath}:`, error);
    return false;
  }
}

async function main() {
  try {
    console.log('Searching for TypeScript and JavaScript files...');
    
    // Find all TS and JS files in the project
    const files = await glob('**/*.{ts,js,mts,mjs}', {
      cwd: rootDir,
      ignore: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/build-test/**']
    });
    
    console.log(`Found ${files.length} TypeScript/JavaScript files.`);
    
    let updatedFiles = 0;
    
    // Process files in parallel
    const results = await Promise.all(
      files.map(file => processFile(path.join(rootDir, file)))
    );
    
    updatedFiles = results.filter(Boolean).length;
    
    console.log(`Removed JSON assertions from ${updatedFiles} files.`);
    
    if (updatedFiles > 0) {
      console.log('Successfully removed all JSON import assertions!');
    } else {
      console.log('No files needed to be updated.');
    }
  } catch (error) {
    console.error('Error processing files:', error);
    process.exit(1);
  }
}

main(); 