// Unified permission ladder shown in the composer's permission picker. Maps a
// curated three-option control (Plan / Ask Permission / Bypass) onto each
// provider's native mode vocabulary, derived purely from the snapshot's mode
// metadata (`plan` id, the default mode, and the `isUnattended` bypass mode).
// `modeId` stays the single wire field sent to the dispatcher — there is no
// separate persisted permission field; the active unified mode is derived from
// the current `modeId`.
import type { ProviderMode } from '@/api/types';

export type PermissionMode = 'plan' | 'ask' | 'bypass';

export const PERMISSION_LABELS: Record<PermissionMode, string> = {
  plan: 'Plan',
  ask: 'Ask Permission',
  bypass: 'Bypass',
};

/** The native modeId for a unified permission, or null when the provider has no
 *  modes (e.g. goose). `plan` → the `plan`-id mode; `bypass` → the `isUnattended`
 *  mode; `ask` → the non-unattended default. Falls back to defaultModeId. */
export function nativeModeForPermission(
  mode: PermissionMode,
  modes: ProviderMode[],
  defaultModeId: string | null,
): string | null {
  if (modes.length === 0) return null;
  if (mode === 'plan') return modes.find((m) => m.id === 'plan')?.id ?? defaultModeId;
  if (mode === 'bypass') return modes.find((m) => m.isUnattended)?.id ?? defaultModeId;
  return (
    modes.find((m) => m.id === defaultModeId && !m.isUnattended)?.id ??
    modes.find((m) => !m.isUnattended && m.id !== 'plan')?.id ??
    defaultModeId
  );
}

/** Which unified permission a native modeId corresponds to (for picker state). */
export function permissionForModeId(modeId: string | null, modes: ProviderMode[]): PermissionMode {
  if (!modeId) return 'ask';
  if (modeId === 'plan') return 'plan';
  if (modes.find((m) => m.id === modeId)?.isUnattended) return 'bypass';
  return 'ask';
}

/** The unified permission options a provider supports, in fixed Plan→Ask→Bypass
 *  order. Empty when the provider exposes no modes (no picker shown). */
export function availablePermissionModes(
  modes: ProviderMode[],
): Array<{ id: PermissionMode; label: string }> {
  if (modes.length === 0) return [];
  const out: Array<{ id: PermissionMode; label: string }> = [];
  if (modes.some((m) => m.id === 'plan')) out.push({ id: 'plan', label: PERMISSION_LABELS.plan });
  out.push({ id: 'ask', label: PERMISSION_LABELS.ask });
  if (modes.some((m) => m.isUnattended)) out.push({ id: 'bypass', label: PERMISSION_LABELS.bypass });
  return out;
}
