#!/usr/bin/env ts-node
/**
 * Fix TypeScript errors in test files
 */

import * as fs from 'fs';
import * as path from 'path';

// Recursively get all test files
function getAllTestFiles(dir: string, fileList: string[] = []): string[] {
  const files = fs.readdirSync(dir);

  for (const file of files) {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      getAllTestFiles(filePath, fileList);
    } else if (file.endsWith('.test.ts') || file.endsWith('.e2e.test.ts')) {
      fileList.push(filePath);
    }
  }

  return fileList;
}

const srcDir = path.join(__dirname, '../src');
const testFiles = getAllTestFiles(srcDir);

let totalChanges = 0;

for (const filePath of testFiles) {
  const file = path.basename(filePath);
  let content = fs.readFileSync(filePath, 'utf-8');
  let changes = 0;

  // Fix 1: Add missing 'description' field to workflow metadata (single-line)
  const workflowMetadataRegex = /workflow:\s*\{\s*id:\s*'([^']+)',\s*version:\s*'([^']+)',\s*name:\s*'([^']+)'\s*\}/g;
  content = content.replace(workflowMetadataRegex, (match, id, version, name) => {
    changes++;
    return `workflow: { id: '${id}', version: '${version}', name: '${name}', description: 'Test workflow' }`;
  });

  // Fix 1b: Add missing 'description' field to workflow metadata (multi-line)
  // Pattern: workflow: {\n        id: 'xxx',\n        version: 'xxx',\n        name: 'xxx',\n      },
  const multiLineWorkflowRegex = /workflow:\s*\{\s*\n\s*id:\s*'([^']+)',\s*\n\s*version:\s*'([^']+)',\s*\n\s*name:\s*'([^']+)',?\s*\n\s*\}/g;
  content = content.replace(multiLineWorkflowRegex, (match, id, version, name) => {
    changes++;
    return `workflow: {\n        id: '${id}',\n        version: '${version}',\n        name: '${name}',\n        description: 'Test workflow',\n      }`;
  });

  // Fix 2: Replace 'main' with 'primary' in database connections
  // Pattern: main: 'xxx'
  // Replace with: primary: 'xxx'
  const mainToPrimaryRegex = /(\s+)main:\s*'([^']+)'/g;
  content = content.replace(mainToPrimaryRegex, (match, indent, value) => {
    changes++;
    return `${indent}primary: '${value}'`;
  });

  // Fix 2b: Replace databases.main with databases.primary
  // Pattern: databases: {\n          main: {
  // Replace with: databases: {\n          primary: {
  const databasesMainRegex = /(databases:\s*\{\s*\n\s*)main:/g;
  content = content.replace(databasesMainRegex, (match, prefix) => {
    changes++;
    return `${prefix}primary:`;
  });

  // Fix 3: Add missing 'primary' field in empty database connections
  // Pattern: connections: {}  (any whitespace)
  // Replace with: connections: { primary: 'postgresql://localhost/test' }
  const emptyConnectionsRegex = /connections:\s*\{\s*\}/g;
  content = content.replace(emptyConnectionsRegex, () => {
    changes++;
    return `connections: { primary: 'postgresql://localhost/test' }`;
  });

  // Fix 4: Add missing 'primary' field in empty databases object
  // Pattern: databases: {}, or databases: {\n      },
  const emptyDatabasesRegex = /databases:\s*\{\s*\}/g;
  content = content.replace(emptyDatabasesRegex, () => {
    changes++;
    return `databases: { primary: 'postgresql://localhost/test' }`;
  });

  // Fix 4b: Multi-line empty databases
  const multiLineEmptyDatabasesRegex = /(databases:\s*\{\s*\n\s*)\}/g;
  content = content.replace(multiLineEmptyDatabasesRegex, (match, prefix) => {
    changes++;
    return `${prefix}  primary: 'postgresql://localhost/test',\n        }`;
  });

  // Fix 5: Add missing executionPlan to GeneratorContext
  // Pattern: { workflow: Workflow; outputDirectory: string; }
  // Replace with: { workflow, outputDirectory, executionPlan: { workflow, componentPlans: new Map() } }
  const generatorContextRegex = /\{\s*workflow(?::\s*workflow)?,\s*outputDirectory:\s*([^}]+)\s*\}/g;
  content = content.replace(generatorContextRegex, (match, outputDir) => {
    // Only replace if this looks like a GeneratorContext argument (in a generate() call)
    if (content.indexOf(match + ')') > -1 || content.indexOf(match + ',') > -1) {
      changes++;
      return `{ workflow, outputDirectory: ${outputDir}, executionPlan: { workflow, componentPlans: new Map() } }`;
    }
    return match;
  });

  // Fix 6: Fix incorrect executionPlan with { components: [], services: [] }
  // Replace with { workflow, componentPlans: new Map() }
  const incorrectExecutionPlanRegex = /executionPlan:\s*\{\s*components:\s*\[\],\s*services:\s*\[\]\s*\}/g;
  content = content.replace(incorrectExecutionPlanRegex, () => {
    changes++;
    return 'executionPlan: { workflow, componentPlans: new Map() }';
  });

  // Fix 7: Replace 'providers' with 'provider' in Analytics interface
  const providersToProviderRegex = /(\s+)providers:\s*/g;
  content = content.replace(providersToProviderRegex, (match, indent) => {
    // Only replace if in analytics context
    if (content.substring(content.lastIndexOf('analytics:', content.indexOf(match)), content.indexOf(match)).length < 200) {
      changes++;
      return `${indent}provider: `;
    }
    return match;
  });

  // Fix 8: Fix database config objects (old format with {type, config}) to connection strings
  //  This is too complex to regex safely - will handle manually

  if (changes > 0) {
    fs.writeFileSync(filePath, content, 'utf-8');
    console.log(`✓ Fixed ${changes} issues in ${file}`);
    totalChanges += changes;
  }
}

console.log(`\n✅ Total: Fixed ${totalChanges} issues across ${testFiles.length} files`);
