import type { ProviderPreset } from './defaultIcon';

export const PROVIDER_EDITABLE_FIELDS = [
  'apiKey',
  'endpoint',
  'chatPath',
  'embedPath',
  'rerankPath',
] as const;

export type ProviderEditableField = (typeof PROVIDER_EDITABLE_FIELDS)[number];

export interface ProviderDraft {
  apiKey: string;
  endpoint: string;
  chatPath: string;
  embedPath: string;
  rerankPath: string;
}

type ProviderLike = Partial<Record<ProviderEditableField, string>> & {
  providerType?: string;
};

export const createProviderDraft = (
  provider?: null | ProviderLike,
): ProviderDraft => ({
  apiKey: provider?.apiKey || '',
  endpoint: provider?.endpoint || '',
  chatPath: provider?.chatPath || '',
  embedPath: provider?.embedPath || '',
  rerankPath: provider?.rerankPath || '',
});

export const isProviderDraftDirty = (
  provider?: null | ProviderLike,
  draft?: null | ProviderLike,
) =>
  PROVIDER_EDITABLE_FIELDS.some(
    (field) => (provider?.[field] || '') !== (draft?.[field] || ''),
  );

export const getProviderConfigMetrics = (
  provider?: null | ProviderLike,
  preset?: ProviderPreset,
) => {
  const requiredFields: ProviderEditableField[] = [
    'apiKey',
    'endpoint',
    'chatPath',
  ];

  if (preset?.options?.embedPath || provider?.embedPath) {
    requiredFields.push('embedPath');
  }

  if (preset?.options?.rerankPath || provider?.rerankPath) {
    requiredFields.push('rerankPath');
  }

  const completed = requiredFields.filter((field) =>
    Boolean((provider?.[field] || '').trim()),
  ).length;
  const total = requiredFields.length;

  return {
    completed,
    total,
    ratio: total === 0 ? 0 : Math.round((completed / total) * 100),
    complete: total > 0 && completed === total,
  };
};
