#!/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, '..');
const gmxsdkDir = path.resolve(rootDir, 'src/Managing.Fastify/src/generated/gmxsdk');

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

// Regex to match JSON imports without any type assertion
const plainJsonImportRegex = /^(import\s+.+?\s+from\s+['"].*?\.json['"])\s*;/gm;

// Regex to match JSON imports with both assert and with patterns (erroneous state)
const doublePatternJsonImportRegex = /^(import\s+.+?\s+from\s+['"].*?\.json['"])\s+assert\s+\{\s*type\s*:\s*['"]json['"]\s*\}\s+with\s+\{\s*type\s*:\s*["']json["']\s*\}\s*;/gm;

// Regex to match JSON imports that already have the with pattern
const withJsonImportRegex = /^(import\s+.+?\s+from\s+['"].*?\.json['"])\s+with\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 for all import patterns
    const hasDoublePattern = doublePatternJsonImportRegex.test(content);
    doublePatternJsonImportRegex.lastIndex = 0;
    
    const hasOldJsonImports = oldJsonImportRegex.test(content);
    oldJsonImportRegex.lastIndex = 0;
    
    const hasPlainJsonImports = plainJsonImportRegex.test(content);
    plainJsonImportRegex.lastIndex = 0;
    
    const hasWithPattern = withJsonImportRegex.test(content);
    withJsonImportRegex.lastIndex = 0;
    
    // If no patterns to fix, return early
    if (!hasDoublePattern && !hasOldJsonImports && !hasPlainJsonImports && !hasWithPattern) {
      return false; // No changes needed
    }
    
    // Apply fixes in sequence
    let updatedContent = content;
    
    // 1. First fix the double pattern errors (both assert and with)
    if (hasDoublePattern) {
      updatedContent = updatedContent.replace(doublePatternJsonImportRegex, '$1 with { type: "json" };');
    }
    
    // 2. Replace assert pattern with with pattern
    if (hasOldJsonImports) {
      updatedContent = updatedContent.replace(oldJsonImportRegex, '$1 with { type: "json" };');
    }
    
    // 3. Add with pattern to plain JSON imports
    if (hasPlainJsonImports) {
      // Process line by line to avoid matching imports that already have with
      const lines = updatedContent.split('\n');
      
      const modifiedLines = lines.map(line => {
        // Check if line is a plain JSON import without assert/with patterns
        if (plainJsonImportRegex.test(line) && !line.includes('assert') && !line.includes('with')) {
          plainJsonImportRegex.lastIndex = 0;
          return line.replace(plainJsonImportRegex, '$1 with { type: "json" };');
        }
        return line;
      });
      
      updatedContent = modifiedLines.join('\n');
    }
    
    // If content changed, write the updated content back to the file
    if (updatedContent !== content) {
      await fs.writeFile(filePath, updatedContent, 'utf8');
      return true; // File was updated
    }
    
    return false; // No changes made
  } catch (error) {
    console.error(`Error processing file ${filePath}:`, error);
    return false;
  }
}

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

main(); 