import { Command } from 'commander';
import { generateKeyPair, exportKeyPair, deriveDID } from '@highway1/core';
import { hasIdentity, setIdentity, setAgentCard } from '../config.js';
import { success, error, spinner, printHeader, printKeyValue } from '../ui.js';

export function registerInitCommand(program: Command): void {
  program
    .command('init')
    .description('Initialize a new Clawiverse identity')
    .option('--name <name>', 'Agent name', 'My Agent')
    .option('--description <description>', 'Agent description', 'A Clawiverse agent')
    .option('--force', 'Overwrite existing identity')
    .action(async (options) => {
      try {
        printHeader('Initialize Clawiverse Identity');

        if (hasIdentity() && !options.force) {
          error('Identity already exists. Use --force to overwrite.');
          process.exit(1);
        }

        const spin = spinner('Generating key pair...');

        const keyPair = await generateKeyPair();
        const exported = exportKeyPair(keyPair);
        const did = deriveDID(keyPair.publicKey);

        setIdentity({
          did,
          publicKey: exported.publicKey,
          privateKey: exported.privateKey,
        });

        setAgentCard({
          name: options.name,
          description: options.description,
          capabilities: [],
        });

        spin.succeed('Identity created successfully!');

        console.log();
        printKeyValue('DID', did);
        printKeyValue('Name', options.name);
        printKeyValue('Description', options.description);
        console.log();

        success('Run "hw1 join" to connect to the network');
      } catch (err) {
        error(`Failed to initialize: ${(err as Error).message}`);
        process.exit(1);
      }
    });
}
