/**
 * End-to-end test for workflow execution and code generation
 */

import { WorkflowParser } from './src/parser/workflow-parser';
import { CodeGenerator } from './src/generators/code-generator';
// Import generators to ensure they're registered
import './src/generators';
import * as path from 'path';

async function main() {
  console.log('Starting end-to-end test...\n');

  // Parse the user-authentication workflow
  console.log('1. Parsing workflow...');
  const parser = new WorkflowParser();
  const workflowPath = path.join(__dirname, 'examples/user-authentication.workflow.yaml');
  const workflow = parser.parseFile(workflowPath);
  console.log(`   ✓ Parsed workflow: ${workflow.workflow.name} v${workflow.workflow.version}`);
  console.log(`   ✓ Stack components: ${Object.keys(workflow.stack).join(', ')}\n`);

  // Generate code
  console.log('2. Generating code...');
  const generator = new CodeGenerator();
  const result = await generator.generate(workflow, {
    outputDirectory: path.join(__dirname, 'generated'),
    dryRun: true, // Don't actually write files, just show what would be generated
    verbose: true,
  });

  // Display results
  console.log('\n3. Generation results:');
  console.log(`   ✓ Files to generate: ${result.files.length}`);

  if (result.warnings.length > 0) {
    console.log(`   ⚠ Warnings: ${result.warnings.length}`);
    result.warnings.forEach(w => console.log(`     - ${w}`));
  }

  if (result.errors.length > 0) {
    console.log(`   ✗ Errors: ${result.errors.length}`);
    result.errors.forEach(e => console.log(`     - ${e}`));
  }

  // Group files by stack component
  console.log('\n4. Generated files by component:');
  const filesByComponent: Record<string, string[]> = {};

  for (const file of result.files) {
    const parts = file.path.split('/');
    const component = parts[parts.indexOf('generated') + 1] || 'root';
    if (!filesByComponent[component]) {
      filesByComponent[component] = [];
    }
    filesByComponent[component].push(file.path.replace(/.*generated\//, ''));
  }

  for (const [component, files] of Object.entries(filesByComponent)) {
    console.log(`\n   ${component}:`);
    files.forEach(f => console.log(`     - ${f}`));
  }

  // Show sample generated content
  console.log('\n5. Sample generated content:');

  // Show React component
  const reactComponent = result.files.find(f => f.path.includes('LoginForm.tsx'));
  if (reactComponent) {
    console.log('\n   React LoginForm Component (first 20 lines):');
    const lines = reactComponent.content.split('\n').slice(0, 20);
    lines.forEach((line, i) => console.log(`     ${String(i + 1).padStart(2, ' ')}: ${line}`));
  }

  // Show backend endpoint
  const backendEndpoint = result.files.find(f => f.path.includes('login-endpoint.ts') && f.path.includes('routes'));
  if (backendEndpoint) {
    console.log('\n   Backend Login Endpoint (first 20 lines):');
    const lines = backendEndpoint.content.split('\n').slice(0, 20);
    lines.forEach((line, i) => console.log(`     ${String(i + 1).padStart(2, ' ')}: ${line}`));
  }

  // Show documentation
  const mainDocs = result.files.find(f => f.path.includes('docs/README.md'));
  if (mainDocs) {
    console.log('\n   Main Documentation (first 15 lines):');
    const lines = mainDocs.content.split('\n').slice(0, 15);
    lines.forEach((line, i) => console.log(`     ${String(i + 1).padStart(2, ' ')}: ${line}`));
  }

  console.log('\n✓ End-to-end test completed successfully!');
  console.log('\nSummary:');
  console.log(`  - Workflow parsed: ${workflow.workflow.id}`);
  console.log(`  - Stack components: ${Object.keys(workflow.stack).length}`);
  console.log(`  - Files generated: ${result.files.length}`);
  console.log(`  - Warnings: ${result.warnings.length}`);
  console.log(`  - Errors: ${result.errors.length}`);
}

main().catch(error => {
  console.error('Error:', error);
  process.exit(1);
});
