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

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

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')) {
      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 type assertions for extendedWorkflow objects with WorkflowRelationship issues
  // Pattern: const extendedWorkflow = { ... }
  // This won't work well with regex, so we'll use a simpler approach

  // Fix 2: Add missing soft_delete to Model definitions
  // Pattern: timestamps: true,
  // Add after it: soft_delete: false,
  const timestampsWithoutSoftDelete = /(\s+timestamps:\s*true,)(\s+\})/g;
  const oldContent1 = content;
  content = content.replace(timestampsWithoutSoftDelete, (match, timestamps, closing) => {
    changes++;
    return `${timestamps}\n      soft_delete: false,${closing}`;
  });

  // Fix 3: Add missing includeExamples and includeCommonIssues to DocumentationIntent
  // Pattern: { type: 'setup_guide', audience: 'developer', overwrite: 'always' }
  // This is complex, let's just add the missing fields
  const intentWithoutRequired = /\{\s*type:\s*'(setup_guide|api_reference|tutorial|architecture|best_practices|troubleshooting)',\s*audience:\s*'(developer|user|both)',\s*overwrite:\s*'(always|if-missing|never)'/g;
  const oldContent2 = content;
  content = content.replace(intentWithoutRequired, (match, type, audience, overwrite) => {
    changes++;
    return `{ type: '${type}', audience: '${audience}', overwrite: '${overwrite}', includeExamples: false, includeCommonIssues: false`;
  });

  // Fix 4: Fix octal escape sequences (if any)
  const octalEscape = /\\0([0-7])/g;
  if (content.match(octalEscape)) {
    content = content.replace(octalEscape, '\\\\0$1');
    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`);
