export type ProviderModelOption = {
  id: string;
  label: string;
  reasoning: boolean;
  toolCall: boolean;
  context?: number;
};

const options = {
  openai: ['gpt-5.1-codex', 'gpt-5.1', 'gpt-5', 'gpt-5-mini'],
  opencode_openai_login: ['gpt-5.1-codex', 'gpt-5.1', 'gpt-5'],
  anthropic: ['claude-sonnet-4-5', 'claude-opus-4-5', 'claude-haiku-4-5'],
  google: ['gemini-3-pro', 'gemini-2.5-pro', 'gemini-2.5-flash'],
  openrouter: ['openai/gpt-5.1-codex', 'anthropic/claude-sonnet-4-5'],
  requesty: ['openai/gpt-5.1-codex', 'anthropic/claude-sonnet-4-5'],
  litellm: ['openai/gpt-5.1-codex', 'anthropic/claude-sonnet-4-5'],
  cloudflare_ai_gateway: ['openai/gpt-5.1-codex'],
  custom_openai_compatible: ['gpt-5.1-codex'],
} as const;

export type ProviderModelKey = keyof typeof options;
const modelOptionsByProvider: Record<string, readonly string[]> = options;

const labelForModel = (id: string) => {
  const label = id
    .split('/')
    .at(-1)
    ?.replaceAll('-', ' ')
    .replace(/\b\w/g, (letter) => letter.toUpperCase());
  return label ?? id;
};

export const suggestedModelOptions = (
  provider: string,
): ProviderModelOption[] =>
  (modelOptionsByProvider[provider] ?? []).map((id) => ({
    id,
    label: labelForModel(id),
    reasoning: true,
    toolCall: true,
  }));

export const modelOptionsFromIds = (
  ids: string[] | undefined,
): ProviderModelOption[] =>
  (ids ?? [])
    .map((id) => id.trim())
    .filter(Boolean)
    .filter((id, index, all) => all.indexOf(id) === index)
    .map((id) => ({
      id,
      label: labelForModel(id),
      reasoning: true,
      toolCall: true,
    }));

export const modelIdsForProfile = (profile?: {
  defaultModel?: string;
  modelOptions?: string[];
}) =>
  [profile?.defaultModel, ...(profile?.modelOptions ?? [])]
    .filter((model): model is string => Boolean(model?.trim()))
    .filter((model, index, all) => all.indexOf(model) === index);

export const supportsCustomModelOptions = (provider: string) =>
  [
    'openrouter',
    'requesty',
    'litellm',
    'cloudflare_ai_gateway',
    'custom_openai_compatible',
  ].includes(provider);
