import type { Command } from 'commander';
import { loadConfigSafe, getConfigPath, redactSecrets } from './shared.js';

/** Format config for display: redact secrets, return as JSON. */
export function formatConfig(config: Record<string, unknown>): string {
  const redacted = redactSecrets(config);
  return JSON.stringify(redacted, null, 2);
}

export function registerConfigCommand(program: Command): void {
  program
    .command('config')
    .description('Show resolved configuration (secrets redacted)')
    .option('-c, --config <path>', 'Config file path')
    .option('--raw', 'Show unredacted config (dangerous)')
    .action(async (opts: { config?: string; raw?: boolean }) => {
      const configPath = opts.config ?? getConfigPath();
      const { config, error } = loadConfigSafe(configPath);

      if (!config) {
        console.error(error);
        process.exit(1);
      }

      console.log(`Config loaded from: ${configPath}`);
      console.log('');

      if (opts.raw) {
        console.log(JSON.stringify(config, null, 2));
      } else {
        console.log(formatConfig(config as unknown as Record<string, unknown>));
      }
    });
}
