export type RuntimeBackendMode = 'config_default' | 'force_native' | 'force_pi_embedded';

export interface RuntimeBackendModeCommandContext {
  getActiveTier: () => string;
  getBackendMode: () => RuntimeBackendMode;
  getConfiguredDefaultBackend: () => string;
  getEffectiveDefaultBackend: () => string;
  getAvailableExternalBackends: () => string[];
  setBackendMode?: (mode: RuntimeBackendMode) => void;
}

function normalizeRuntimeInput(inputRaw: string): string {
  let normalized = inputRaw.trim().toLowerCase();
  // Accept subcommand-only input and accidental full command input.
  normalized = normalized.replace(/^(?:\/)?(?:runtime|backend)\b/, '').trim();
  normalized = normalized.replace(/^\//, '').trim();
  return normalized;
}

export function formatRuntimeBackendStatusLine(ctx: RuntimeBackendModeCommandContext): string {
  const availableExternal = [...ctx.getAvailableExternalBackends()].sort().join(', ') || 'none';
  return [
    `Flynn is running. Active model tier: ${ctx.getActiveTier()}. Backend: ${ctx.getEffectiveDefaultBackend()}`,
    `Backend mode: ${ctx.getBackendMode()}`,
    `Configured default: ${ctx.getConfiguredDefaultBackend()}`,
    `Available external backends: ${availableExternal}`,
  ].join('\n');
}

export function executeRuntimeBackendModeCommand(
  inputRaw: string,
  ctx: RuntimeBackendModeCommandContext,
): string {
  const normalized = normalizeRuntimeInput(inputRaw);

  if (!normalized || normalized === 'status' || normalized === 'show') {
    return formatRuntimeBackendStatusLine(ctx);
  }

  if (!ctx.setBackendMode) {
    return 'Backend mode control is not available in this runtime.';
  }

  if (
    normalized === 'activate pi'
    || normalized === 'activate pi_embedded'
    || normalized === 'activate pi-embedded'
  ) {
    ctx.setBackendMode('force_pi_embedded');
    return [
      'Pi embedded backend activated globally.',
      formatRuntimeBackendStatusLine(ctx),
    ].join('\n\n');
  }

  if (
    normalized === 'deactivate pi'
    || normalized === 'deactivate pi_embedded'
    || normalized === 'deactivate pi-embedded'
  ) {
    ctx.setBackendMode('force_native');
    return [
      'Pi embedded backend deactivated globally. Native is now forced for Pi-routed turns.',
      formatRuntimeBackendStatusLine(ctx),
    ].join('\n\n');
  }

  if (
    normalized === 'use config'
    || normalized === 'reset'
    || normalized === 'auto'
    || normalized === 'config'
  ) {
    ctx.setBackendMode('config_default');
    return [
      'Backend mode reset to config default.',
      formatRuntimeBackendStatusLine(ctx),
    ].join('\n\n');
  }

  return [
    'Usage:',
    '/runtime status',
    '/runtime activate pi',
    '/runtime deactivate pi',
    '/runtime use config',
    '',
    'Alias:',
    '/backend status',
    '/backend activate pi',
    '/backend deactivate pi',
    '/backend use config',
  ].join('\n');
}
