/**
 * Validate command
 * Validates workflow files
 */

import * as path from 'path';
import * as fs from 'fs';
import chalk from 'chalk';
import ora from 'ora';
import { WorkflowParser } from '../../parser/workflow-parser';
import { WorkflowEngine } from '../../engine/workflow-engine';

interface ValidateOptions {
  directory: boolean;
}

export async function validateCommand(workflowPath: string, options: ValidateOptions) {
  const spinner = ora();

  try {
    const absolutePath = path.resolve(process.cwd(), workflowPath);

    // Check if path exists
    if (!fs.existsSync(absolutePath)) {
      console.error(chalk.red('✗ Error:'), `Path not found: ${workflowPath}`);
      process.exit(1);
    }

    const parser = new WorkflowParser();
    const engine = new WorkflowEngine();

    if (options.directory || fs.statSync(absolutePath).isDirectory()) {
      // Validate directory
      spinner.start('Validating workflows in directory...');

      const parseResults = await parser.parseDirectory(absolutePath);
      spinner.succeed(chalk.green(`✓ Found ${parseResults.length} workflow(s)`));

      let totalErrors = 0;
      let totalWarnings = 0;

      for (const parseResult of parseResults) {
        const workflow = parseResult.workflow;
        console.log();
        console.log(chalk.bold(`${workflow.workflow.id}:`));

        const validation = engine.validate(workflow);

        if (validation.valid) {
          console.log(chalk.green(`  ✓ Valid`));
        } else {
          console.log(chalk.red(`  ✗ Invalid`));
        }

        if (validation.errors.length > 0) {
          console.log(chalk.red(`  Errors:`));
          validation.errors.forEach(e => console.log(chalk.red(`    - ${e}`)));
          totalErrors += validation.errors.length;
        }

        if (validation.warnings.length > 0) {
          console.log(chalk.yellow(`  Warnings:`));
          validation.warnings.forEach(w => console.log(chalk.yellow(`    - ${w}`)));
          totalWarnings += validation.warnings.length;
        }
      }

      console.log();
      console.log(chalk.bold('Summary:'));
      console.log(`  Workflows: ${parseResults.length}`);
      console.log(chalk.red(`  Errors: ${totalErrors}`));
      console.log(chalk.yellow(`  Warnings: ${totalWarnings}`));

      if (totalErrors > 0) {
        process.exit(1);
      }

    } else {
      // Validate single file
      spinner.start('Validating workflow...');

      const parseResult = await parser.parseFile(absolutePath);
      const workflow = parseResult.workflow;
      const validation = engine.validate(workflow);

      if (validation.valid) {
        spinner.succeed(chalk.green('✓ Workflow is valid'));
      } else {
        spinner.fail(chalk.red('✗ Workflow is invalid'));
      }

      console.log();
      console.log(chalk.bold(`${workflow.workflow.name} (${workflow.workflow.id}):`));
      console.log(chalk.dim(`  Version: ${workflow.workflow.version}`));
      console.log(chalk.dim(`  Stack components: ${Object.keys(workflow.stack).length}`));

      if (validation.errors.length > 0) {
        console.log();
        console.log(chalk.red('Errors:'));
        validation.errors.forEach(e => console.log(chalk.red(`  - ${e}`)));
      }

      if (validation.warnings.length > 0) {
        console.log();
        console.log(chalk.yellow('Warnings:'));
        validation.warnings.forEach(w => console.log(chalk.yellow(`  - ${w}`)));
      }

      if (!validation.valid) {
        process.exit(1);
      }
    }

  } catch (error) {
    spinner.fail(chalk.red('✗ Validation failed'));

    if (error instanceof Error) {
      console.error(chalk.red('Error:'), error.message);
    } else {
      console.error(chalk.red('Error:'), String(error));
    }

    process.exit(1);
  }
}
