import chalk from 'chalk';
import Table from 'cli-table3';
import { parseVersions } from '../utils/versions.js';

export function registerListCommand(program) {
  program
    .command('list')
    .description('List all available skills')
    .option('-t, --type <type>', 'Filter by type: builtin or store')
    .option('--json', 'Output as JSON')
    .action(async (opts) => {
      try {
        let skills = await parseVersions();

        if (opts.type) {
          const t = opts.type.toLowerCase();
          skills = skills.filter((s) => s.types.includes(t));
        }

        if (skills.length === 0) {
          if (opts.json) {
            console.log('[]');
          } else {
            console.log(chalk.yellow('No skills found.'));
          }
          return;
        }

        if (opts.json) {
          console.log(JSON.stringify(skills, null, 2));
          return;
        }

        const hasDisplayInfo = skills.some((s) => s.displayName || s.description);

        const head = [
          chalk.cyan('Skill'),
          chalk.cyan('Types'),
          chalk.cyan('Version'),
        ];
        if (hasDisplayInfo) {
          head.push(chalk.cyan('Display Name'), chalk.cyan('Description'));
        }

        const table = new Table({
          head,
          style: { head: [], border: [] },
        });

        for (const s of skills) {
          const typesStr = s.types
            .map((t) => (t === 'builtin' ? chalk.blue(t) : chalk.green(t)))
            .join(', ');
          const row = [s.name, typesStr, s.version];
          if (hasDisplayInfo) {
            row.push(s.displayName, s.description);
          }
          table.push(row);
        }

        console.log();
        console.log(table.toString());
        console.log();
        console.log(chalk.gray(`  Total: ${skills.length} skills`));
        console.log();
      } catch (err) {
        console.error(chalk.red(`Failed to list skills: ${err.message}`));
        process.exit(1);
      }
    });
}
