#!/usr/bin/env node

// Polyfill for Node.js < v22.0.0
if (!Promise.withResolvers) {
  Promise.withResolvers = function <T>() {
    let resolve: (value: T | PromiseLike<T>) => void;
    let reject: (reason?: any) => void;
    const promise = new Promise<T>((res, rej) => {
      resolve = res;
      reject = rej;
    });
    return { promise, resolve: resolve!, reject: reject! };
  };
}

import { Command } from 'commander';
import { createRequire } from 'module';
import { registerInitCommand } from './commands/init.js';
import { registerJoinCommand } from './commands/join.js';
import { registerDiscoverCommand } from './commands/discover.js';
import { registerSendCommand } from './commands/send.js';
import { registerStatusCommand } from './commands/status.js';
import { registerIdentityCommand } from './commands/identity.js';
import { registerCardCommand } from './commands/card.js';
import { createTrustCommand } from './commands/trust.js';

const require = createRequire(import.meta.url);
const { version } = require('../package.json');

const program = new Command();

const binName = process.argv[1]?.includes('hw1') ? 'hw1' : 'clawiverse';

program
  .name(binName)
  .description('CLI tool for decentralized AI agent communication')
  .version(version);

// Register commands
registerInitCommand(program);
registerJoinCommand(program);
registerDiscoverCommand(program);
registerSendCommand(program);
registerStatusCommand(program);
registerIdentityCommand(program);
registerCardCommand(program);
program.addCommand(createTrustCommand());

program.parse();
