/**
 * Client-side, display-only feature → model resolution.
 *
 * Mirrors a simplified version of cms-core's `resolveFeatureModel` so the UI can
 * preview which model a feature will use as the admin edits — including before
 * Save. The server resolver remains the authority for the AI runtime; this only
 * drives labels and capability warnings.
 */

import type { AiModelView } from './useAiSettings.js'

const CAPABILITY_LABELS: Record<string, string> = {
  text: 'text',
  vision: 'vision',
  imageGeneration: 'image generation',
  embeddings: 'embeddings',
  toolCalling: 'tool calling',
  structuredOutput: 'structured output',
  streaming: 'streaming',
  reasoning: 'reasoning',
  longContext: 'long context',
}

export function findModel(models: AiModelView[], id: string | undefined): AiModelView | undefined {
  if (!id) return undefined
  return models.find((m) => m.id === id || m.providerModelId === id)
}

/** Required capabilities a model is missing. Unknown capability strings are ignored. */
export function missingCapabilities(model: AiModelView | undefined, required: string[]): string[] {
  const wanted = required.filter((c) => c in CAPABILITY_LABELS)
  if (!model) return wanted
  return wanted.filter((c) => !model.capabilities?.[c])
}

export function capabilityLabel(key: string): string {
  return CAPABILITY_LABELS[key] ?? key
}

export interface EffectiveFeatureModel {
  /** The id that will be used (override, else the global default). */
  modelId: string
  model?: AiModelView
  /** True when the feature has its own model override (not the default). */
  isOverride: boolean
  missingCapabilities: string[]
}

export function effectiveFeatureModel(
  override: string | undefined,
  defaultModelId: string,
  required: string[],
  models: AiModelView[],
): EffectiveFeatureModel {
  const isOverride = Boolean(override)
  const modelId = override || defaultModelId
  const model = findModel(models, modelId)
  return { modelId, model, isOverride, missingCapabilities: missingCapabilities(model, required) }
}

/** Whether a model satisfies every required capability and is selectable. */
export function isModelCompatible(model: AiModelView, required: string[]): boolean {
  return model.status !== 'unavailable' && missingCapabilities(model, required).length === 0
}
