/**
 * Commit command
 * Creates a commit of config.yaml changes
 */

import * as path from 'path';
import * as fs from 'fs';
import chalk from 'chalk';
import ora from 'ora';
import { CommitManager } from '../../commit/commit-manager';

interface CommitOptions {
  message?: string;
  author?: string;
}

export async function commitCommand(options: CommitOptions) {
  const spinner = ora();

  try {
    const projectRoot = process.cwd();

    // Check if .bangstack exists
    const bangstackPath = path.join(projectRoot, '.bangstack');
    if (!fs.existsSync(bangstackPath)) {
      console.error(chalk.red('✗ Error:'), 'Not a Bangstack project. Run "bangstack init" first.');
      process.exit(1);
    }

    // Check if config.yaml exists
    const configPath = path.join(bangstackPath, 'config.yaml');
    if (!fs.existsSync(configPath)) {
      console.error(chalk.red('✗ Error:'), 'No config.yaml found. Create one first.');
      process.exit(1);
    }

    // Get commit message
    const message = options.message || 'Update configuration';

    // Create commit manager
    const commitManager = new CommitManager(projectRoot);

    spinner.start('Creating commit...');

    // Create commit
    const commit = await commitManager.createCommit({
      message,
      author: options.author,
    });

    spinner.succeed(chalk.green('✓ Commit created'));

    // Show commit info
    console.log();
    console.log(chalk.bold('Commit:'), chalk.cyan(commit.hash));
    console.log(chalk.bold('Author:'), commit.author);
    console.log(chalk.bold('Date:'), new Date(commit.timestamp).toLocaleString());
    console.log(chalk.bold('Message:'), commit.message);
    console.log();

    // Show diff summary
    const summary = commitManager.getDiffEngine().getSummary(commit.diff);
    console.log(chalk.bold('Changes:'));
    console.log(chalk.green(`  ${summary.added} added`));
    console.log(chalk.yellow(`  ${summary.modified} modified`));
    console.log(chalk.red(`  ${summary.removed} removed`));
    console.log();

    // Show affected files if any
    if (commit.filesAffected && commit.filesAffected.length > 0) {
      console.log(chalk.bold('Files that will be affected on next generate:'));
      commit.filesAffected.forEach(file => {
        console.log(chalk.dim(`  ${file}`));
      });
      console.log();
    }

    console.log(chalk.dim('Run "bangstack log" to view commit history'));
    console.log(chalk.dim('Run "bang generate" to regenerate affected files'));

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

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

    process.exit(1);
  }
}
