/**
 * Card Generator Tool - 工具入口
 */

const CardGenerator = require('../../shared/libs/card-generator');
const Formatter = require('../../shared/libs/card-generator/formatter');
const logger = require('../../shared/logger');

const TOOL_NAME = 'card-generator';

/**
 * 执行卡生成
 * @param {Object} options - 选项
 */
function execute(options) {
  try {
    const generator = new CardGenerator();
    const formatter = new Formatter();

    const type = options.type || 'unionpay';
    const count = parseInt(options.count || 1);
    const format = options.format || 'pipe';

    // 验证卡类型
    const supportedTypes = generator.getSupportedTypes().map(t => t.id);
    if (!supportedTypes.includes(type)) {
      logger.error(TOOL_NAME, `不支持的卡类型: ${type}`);
      logger.info(TOOL_NAME, `支持的类型: ${supportedTypes.join(', ')}`);
      process.exit(1);
    }

    // 生成卡
    let cards;
    if (count === 1) {
      cards = [generator.generate(type)];
    } else {
      cards = generator.generateBatch(count, type);
    }

    // 格式化输出
    const output = formatter.formatBatch(cards, format);
    console.log(output);

    if (count > 1) {
      logger.success(TOOL_NAME, `成功生成 ${count} 张 ${type} 卡`);
    }

  } catch (error) {
    logger.error(TOOL_NAME, error.message);
    process.exit(1);
  }
}

/**
 * 列出支持的卡类型
 */
function listTypes() {
  const generator = new CardGenerator();
  const types = generator.getSupportedTypes();
  
  console.log('\n支持的卡类型:\n');
  types.forEach(type => {
    console.log(`  ${type.id.padEnd(15)} - ${type.name}`);
  });
  console.log('');
}

/**
 * 列出支持的输出格式
 */
function listFormats() {
  const formatter = new Formatter();
  const formats = formatter.getSupportedFormats();
  
  console.log('\n支持的输出格式:\n');
  formats.forEach(format => {
    console.log(`  ${format.id.padEnd(15)} - ${format.name}`);
  });
  console.log('');
}

module.exports = {
  name: TOOL_NAME,
  alias: 'card',
  description: '生成虚拟信用卡号',
  execute,
  listTypes,
  listFormats
};
