#!/usr/bin/env node
/**
 * Bangstack CLI
 * Command-line interface for generating code from workflows
 */

import { Command } from 'commander';
import chalk from 'chalk';
import { generateCommand } from './commands/generate';
import { validateCommand } from './commands/validate';
import { verifyCommand } from './commands/verify';
import { listGeneratorsCommand } from './commands/list-generators';
import { initCommand } from './commands/init';
import { createWorkflowCommand } from './commands/create-workflow';
import { commitCommand } from './commands/commit';
import { logCommand } from './commands/log';
import { showCommand } from './commands/show';
import { registerVersionCommands } from './version-commands';
import * as packageJson from '../../package.json';

const program = new Command();

program
  .name('bangstack')
  .description('Generate production-ready code from workflow definitions')
  .version(packageJson.version);

// Generate command
program
  .command('generate <workflow>')
  .description('Generate code from a workflow file')
  .option('-o, --output <directory>', 'Output directory for generated code (supports relative or absolute paths)', '.')
  .option('-d, --dry-run', 'Show what would be generated without writing files', false)
  .option('-v, --verbose', 'Show detailed output', false)
  .option('-r, --resume', 'Resume from last checkpoint after failure', false)
  .option('--no-checkpoint', 'Disable checkpoint system', false)
  .option('--no-retry', 'Disable automatic retry for transient failures', false)
  .option('--max-retries <number>', 'Maximum retry attempts', parseInt, 3)
  .action(generateCommand);

// Validate command
program
  .command('validate <workflow>')
  .description('Validate a workflow file')
  .option('-d, --directory', 'Validate all workflow files in a directory', false)
  .action(validateCommand);

// Verify command
program
  .command('verify <workflow>')
  .description('Verify workflow and check for dependency mismatches')
  .option('-o, --output <directory>', 'Output directory to check against', process.cwd())
  .option('-v, --verbose', 'Show detailed output', false)
  .action(verifyCommand);

// List generators command
program
  .command('list-generators')
  .alias('list')
  .description('List all available code generators')
  .option('-v, --verbose', 'Show detailed information about each generator', false)
  .option('-c, --category <category>', 'Filter by category (frontend, backend, database, test, documentation)')
  .action(listGeneratorsCommand);

// Init command
program
  .command('init [project-name]')
  .description('Initialize a new project with optional preset')
  .option('-p, --preset <preset>', 'Use a preset stack (mern, next-trpc, django-react, etc.)')
  .option('--example', 'Create with example workflow', false)
  .action(initCommand);

// Create workflow command
program
  .command('create')
  .alias('new')
  .description('Create a new workflow interactively')
  .action(createWorkflowCommand);

// Commit command
program
  .command('commit')
  .description('Create a commit of config.yaml changes')
  .option('-m, --message <message>', 'Commit message')
  .option('-a, --author <author>', 'Commit author (defaults to git config)')
  .action(commitCommand);

// Log command
program
  .command('log')
  .description('Show commit history')
  .option('-n, --limit <number>', 'Limit number of commits to show', parseInt)
  .option('--oneline', 'Show one commit per line', false)
  .action(logCommand);

// Show command
program
  .command('show <hash>')
  .description('Show details of a specific commit')
  .option('--stat', 'Show only statistics, not full diff', false)
  .action(showCommand);

// Register version commands
registerVersionCommands(program);

// Custom help display
program.on('--help', () => {
  console.log('');
  console.log('Examples:');
  console.log('  $ bang create                                    # Interactive workflow creation');
  console.log('  $ bang init my-app --preset mern                # Initialize with MERN preset');
  console.log('  $ bang generate workflow.yaml --output ./app    # Generate code');
  console.log('  $ bang validate workflow.yaml                   # Validate workflow');
  console.log('  $ bang list-generators                          # List available generators');
  console.log('');
  console.log('Quick Start:');
  console.log('  1. Create a new project:      bang init my-app');
  console.log('  2. Edit the workflow:         cd my-app && edit workflows/my-app.workflow.yaml');
  console.log('  3. Generate code:             bang generate workflows/my-app.workflow.yaml');
  console.log('');
  console.log('Learn more: https://github.com/mogullabs/bangstack');
});

// Parse arguments
program.parse(process.argv);

// Show enhanced help if no command provided
if (!process.argv.slice(2).length) {
  console.log('');
  console.log(chalk.cyan.bold('┌─────────────────────────────────────────────────────┐'));
  console.log(chalk.cyan.bold('│') + '  ' + chalk.white.bold('Bangstack') + ' - Code Generation from Workflows  ' + chalk.cyan.bold('│'));
  console.log(chalk.cyan.bold('└─────────────────────────────────────────────────────┘'));
  console.log('');
  console.log(chalk.bold('Quick Start Commands:'));
  console.log('  ' + chalk.cyan('bang create') + '        Create a new workflow interactively');
  console.log('  ' + chalk.cyan('bang init') + '          Initialize a new project');
  console.log('  ' + chalk.cyan('bang generate') + '      Generate code from a workflow');
  console.log('  ' + chalk.cyan('bang list') + '          List available generators');
  console.log('');
  console.log(chalk.bold('Need help?'));
  console.log('  ' + chalk.gray('Run') + ' ' + chalk.cyan('bang --help') + ' ' + chalk.gray('to see all commands'));
  console.log('  ' + chalk.gray('Run') + ' ' + chalk.cyan('bang <command> --help') + ' ' + chalk.gray('for command-specific help'));
  console.log('');
  console.log(chalk.gray('Documentation: https://github.com/mogullabs/bangstack'));
  console.log('');
  process.exit(0);
}
