/**
 * Log command
 * Shows commit history
 */

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

interface LogOptions {
  limit?: number;
  oneline?: boolean;
}

export async function logCommand(options: LogOptions) {
  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);
    }

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

    // Get history
    const history = commitManager.getHistory(options.limit);

    if (history.length === 0) {
      console.log(chalk.dim('No commits yet. Run "bangstack commit" to create your first commit.'));
      return;
    }

    // Display history
    if (options.oneline) {
      // One-line format
      history.forEach(commit => {
        console.log(
          chalk.cyan(commit.hash),
          chalk.dim('•'),
          commit.message
        );
      });
    } else {
      // Full format
      history.forEach((commit, index) => {
        if (index > 0) console.log(); // Spacing between commits

        console.log(chalk.yellow('commit'), chalk.cyan(commit.hash));
        console.log(chalk.bold('Author:'), commit.author);
        console.log(chalk.bold('Date:'), new Date(commit.timestamp).toLocaleString());
        console.log();
        console.log('   ', commit.message);
      });
    }

    console.log();

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

    process.exit(1);
  }
}
