import { Command } from 'commander';
import { getAgentCard, setAgentCard } from '../config.js';
import { success, error, printHeader } from '../ui.js';
import inquirer from 'inquirer';

export function registerCardCommand(program: Command): void {
  const card = program.command('card').description('Manage Agent Card');

  card
    .command('show')
    .description('Show current Agent Card')
    .action(async () => {
      try {
        printHeader('Agent Card');

        const agentCard = getAgentCard();

        if (!agentCard) {
          error('No Agent Card found. Run "hw1 init" first.');
          process.exit(1);
        }

        console.log(JSON.stringify(agentCard, null, 2));
      } catch (err) {
        error(`Failed to show card: ${(err as Error).message}`);
        process.exit(1);
      }
    });

  card
    .command('edit')
    .description('Edit Agent Card')
    .action(async () => {
      try {
        printHeader('Edit Agent Card');

        const currentCard = getAgentCard();

        if (!currentCard) {
          error('No Agent Card found. Run "hw1 init" first.');
          process.exit(1);
        }

        const answers = await inquirer.prompt([
          {
            type: 'input',
            name: 'name',
            message: 'Agent name:',
            default: currentCard.name,
          },
          {
            type: 'input',
            name: 'description',
            message: 'Agent description:',
            default: currentCard.description,
          },
          {
            type: 'input',
            name: 'capabilities',
            message: 'Capabilities (comma-separated):',
            default: currentCard.capabilities.join(', '),
          },
        ]);

        const updatedCard = {
          name: answers.name,
          description: answers.description,
          capabilities: answers.capabilities
            .split(',')
            .map((c: string) => c.trim())
            .filter((c: string) => c.length > 0),
        };

        setAgentCard(updatedCard);

        success('Agent Card updated successfully!');
      } catch (err) {
        error(`Failed to edit card: ${(err as Error).message}`);
        process.exit(1);
      }
    });
}
