/**
 * `workflow cleanup` — Remove old workflow run artifacts.
 *
 * Default retention: 7 days. Removes run data older than the specified
 * number of days.
 *
 * @example
 *   workflow cleanup
 *   workflow cleanup 30 --json
 */

import { printJson, type CliOptions } from "../utils.js";

// ---------------------------------------------------------------------------
// Stub: engine integration (not implemented yet)
// ---------------------------------------------------------------------------

interface CleanupResult {
  removedRuns: number;
  removedEvents: number;
  freedBytes: number;
  retentionDays: number;
}

async function cleanupWorkflowRuns(
  _days: number,
  _cwd?: string,
): Promise<CleanupResult> {
  throw new Error('not implemented yet: cleanupWorkflowRuns');
}

// ---------------------------------------------------------------------------
// Command handler
// ---------------------------------------------------------------------------

export async function cleanupCommand(
  args: string[],
  options: CliOptions,
): Promise<void> {
  // First positional arg is the number of days (default 7).
  const days = args.length > 0 ? parseInt(args[0]!, 10) : 7;

  if (isNaN(days) || days < 1) {
    throw new Error(`Invalid retention days: ${args[0]}. Must be a positive integer.`);
  }

  const result = await cleanupWorkflowRuns(days, options.cwd);

  if (options.json) {
    printJson(result);
    return;
  }

  console.log(`Cleanup complete (retention: ${result.retentionDays} days).`);
  console.log(`  Runs removed: ${result.removedRuns}`);
  console.log(`  Events removed: ${result.removedEvents}`);
  console.log(`  Space freed: ${formatBytes(result.freedBytes)}`);
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB'];
  const i = Math.min(
    Math.floor(Math.log(bytes) / Math.log(1024)),
    units.length - 1,
  );
  const value = bytes / Math.pow(1024, i);
  return `${value.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
}