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';
import inquirer from 'inquirer';

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

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

        // Prompt for agent details if not provided
        let name = options.name;
        let description = options.description;

        if (!name) name = 'My Agent';
        if (!description) description = 'A Clawiverse agent';

        if (!options.name) {
          const { name: inputName } = await inquirer.prompt({
            type: 'input', name: 'name', message: 'Agent name:', default: name,
          });
          name = inputName || name;
        }
        if (!options.description) {
          const { description: inputDesc } = await inquirer.prompt({
            type: 'input', name: 'description', message: 'Agent description:', default: description,
          });
          description = inputDesc || description;
        }

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

        // Generate key pair
        const keyPair = await generateKeyPair();
        const exported = exportKeyPair(keyPair);
        const did = deriveDID(keyPair.publicKey);

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

        // Save agent card
        setAgentCard({
          name,
          description,
          capabilities: [],
        });

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

        console.log();
        printKeyValue('DID', did);
        printKeyValue('Name', name);
        printKeyValue('Description', 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);
      }
    });
}
