import type { Command } from 'commander';
import { getDataDir, loadConfigSafe } from './shared.js';
import { runBackupSnapshot } from '../backup/index.js';

export function registerBackupCommand(program: Command): void {
  program
    .command('backup')
    .description('Create a snapshot backup and optionally upload to MinIO')
    .option('-c, --config <path>', 'Config file path')
    .option('--data-dir <path>', 'Data directory (defaults to FLYNN_DATA_DIR or ~/.local/share/flynn)')
    .option('--no-upload', 'Disable MinIO upload for this run')
    .action(async (opts: { config?: string; dataDir?: string; upload?: boolean }) => {
      const { config, error } = loadConfigSafe(opts.config);
      if (!config) {
        console.error(error);
        process.exit(1);
      }

      const backupConfig = {
        ...config.backup,
        minio: {
          ...config.backup.minio,
          enabled: opts.upload === false ? false : config.backup.minio.enabled,
        },
      };

      const dataDir = opts.dataDir ?? getDataDir();
      const result = await runBackupSnapshot({
        dataDir,
        backupConfig,
      });

      console.log(`Backup archive: ${result.archivePath}`);
      if (result.uploaded && result.remotePath) {
        console.log(`Uploaded to MinIO: ${result.remotePath}`);
      } else {
        console.log('MinIO upload skipped.');
      }
    });
}
