#!/usr/bin/env ts-node
/**
 * Fix final remaining TypeScript errors
 */

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 to workflow metadata
  // Pattern: workflow: { id: 'x', name: 'x', version: 'x' }
  // Replace with: workflow: { id: 'x', name: 'x', version: 'x', description: 'Test workflow' }
  const workflowWithoutDescRegex = /workflow:\s*\{\s*id:\s*['"]([^'"]+)['"],\s*name:\s*['"]([^'"]+)['"],\s*version:\s*['"]([^'"]+)['"]\s*\}/g;
  const oldContent1 = content;
  content = content.replace(workflowWithoutDescRegex, (match, id, name, version) => {
    changes++;
    return `workflow: { id: '${id}', name: '${name}', version: '${version}', description: 'Test workflow' }`;
  });

  // Fix 1b: Multi-line version
  // Pattern:
  //   workflow: {
  //     id: 'x',
  //     name: 'x',
  //     version: 'x'
  //   }
  const multiLineWorkflowRegex = /workflow:\s*\{[\s\n]*id:\s*['"]([^'"]+)['"],[\s\n]*name:\s*['"]([^'"]+)['"],[\s\n]*version:\s*['"]([^'"]+)['"][\s\n]*\}/g;
  const oldContent1b = content;
  content = content.replace(multiLineWorkflowRegex, (match, id, name, version) => {
    changes++;
    return `workflow: {\n        id: '${id}',\n        name: '${name}',\n        version: '${version}',\n        description: 'Test workflow'\n      }`;
  });

  // Fix 2: Add missing executionPlan to GeneratorContext
  // Pattern: { workflow: Workflow; extendedWorkflow: undefined; outputDirectory: string; }
  // Replace with: { workflow, extendedWorkflow: undefined, outputDirectory: outputDir, executionPlan: { workflow, componentPlans: new Map() } }
  const contextWithoutPlanRegex = /\{\s*workflow:\s*Workflow;\s*extendedWorkflow:\s*undefined;\s*outputDirectory:\s*string;\s*\}/g;
  const oldContent2 = content;
  content = content.replace(contextWithoutPlanRegex, () => {
    changes++;
    return '{ workflow, extendedWorkflow: undefined, outputDirectory: outputDir, executionPlan: { workflow, componentPlans: new Map() } }';
  });

  // Fix 3: Fix rate-limiting import
  // Pattern: import { GeneratorContext, Workflow } from '../../types/workflow';
  // Replace with: import { GeneratorContext } from '../types';\nimport { Workflow } from '../../types/workflow';
  if (file === 'enhanced-rate-limiting-generator.test.ts') {
    const oldContent3 = content;
    content = content.replace(
      /import \{ GeneratorContext, Workflow \} from '\.\.\/\.\.\/types\/workflow';/g,
      "import { GeneratorContext } from '../types';\nimport { Workflow } from '../../types/workflow';"
    );
    if (content !== oldContent3) {
      changes++;
    }
  }

  // Fix 4: Fix incorrect enum values in testing generator
  // Pattern: database_strategy: 'sqlite_memory'
  // Replace with: database_strategy: 'sqlite'
  if (file === 'enhanced-testing-generator.test.ts') {
    const oldContent4a = content;
    content = content.replace(/database_strategy:\s*['"]sqlite_memory['"]/g, "database_strategy: 'sqlite'");
    if (content !== oldContent4a) {
      changes++;
    }

    // Pattern: cleanup_strategy: 'recreate'
    // Replace with: cleanup_strategy: 'drop_and_recreate'
    const oldContent4b = content;
    content = content.replace(/cleanup_strategy:\s*['"]recreate['"]/g, "cleanup_strategy: 'drop_and_recreate'");
    if (content !== oldContent4b) {
      changes++;
    }
  }

  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`);
