import { Command } from 'commander';
import chalk from 'chalk';
import { requireConfig } from '../config';
import { apiRequest } from '../api';

interface Agent {
  id: string;
  name: string;
  status: string;
  createdAt: string;
  description?: string;
}

interface AgentsResponse {
  agents: Agent[];
  total?: number;
}

function truncate(str: string, maxLen: number): string {
  if (str.length <= maxLen) return str;
  return str.slice(0, maxLen - 1) + '…';
}

function padEnd(str: string, len: number): string {
  return str.padEnd(len, ' ');
}

export function registerListAgents(program: Command): void {
  program
    .command('list-agents')
    .description('List all registered agents')
    .action(async () => {
      const config = requireConfig();

      try {
        const data = await apiRequest<AgentsResponse | Agent[]>(
          config,
          '/agents',
        );

        const agents: Agent[] = Array.isArray(data)
          ? data
          : (data as AgentsResponse).agents ?? [];

        if (agents.length === 0) {
          console.log(chalk.yellow('No agents found.'));
          return;
        }

        const ID_W = 26;
        const NAME_W = 24;
        const STATUS_W = 10;
        const DATE_W = 20;

        const header =
          chalk.bold(padEnd('AGENT ID', ID_W)) +
          '  ' +
          chalk.bold(padEnd('NAME', NAME_W)) +
          '  ' +
          chalk.bold(padEnd('STATUS', STATUS_W)) +
          '  ' +
          chalk.bold('CREATED AT');

        const divider = chalk.dim(
          '─'.repeat(ID_W + NAME_W + STATUS_W + DATE_W + 6),
        );

        console.log(header);
        console.log(divider);

        for (const agent of agents) {
          const statusColor =
            agent.status === 'active'
              ? chalk.green
              : agent.status === 'inactive'
                ? chalk.yellow
                : chalk.red;

          const createdAt = new Date(agent.createdAt).toLocaleString();

          console.log(
            chalk.cyan(padEnd(truncate(agent.id, ID_W), ID_W)) +
              '  ' +
              padEnd(truncate(agent.name, NAME_W), NAME_W) +
              '  ' +
              statusColor(padEnd(truncate(agent.status, STATUS_W), STATUS_W)) +
              '  ' +
              chalk.dim(truncate(createdAt, DATE_W)),
          );
        }

        console.log(divider);
        const total = Array.isArray(data)
          ? agents.length
          : ((data as AgentsResponse).total ?? agents.length);
        console.log(chalk.dim(`Total: ${total}`));
      } catch (err) {
        console.error(
          chalk.red('Error:'),
          err instanceof Error ? err.message : String(err),
        );
        process.exit(1);
      }
    });
}
