import type { ProviderConfig, ProviderReplayConfig } from "@best-agent/protocol";
import { normalizeProviderConfig } from "./provider-metadata.js";

export function sanitizeProviderReplayConfig(
  config: ProviderConfig | ProviderReplayConfig | undefined,
): ProviderReplayConfig | undefined {
  if (!config) return undefined;

  const safe = { ...normalizeProviderConfig(config as ProviderConfig) } as ProviderReplayConfig & {
    apiKey?: string;
  };
  delete safe.apiKey;
  return safe;
}

export function toProviderReplayConfig(config: ProviderConfig): ProviderReplayConfig {
  return sanitizeProviderReplayConfig(config)!;
}

export function providerReplayIdentity(config: ProviderConfig | ProviderReplayConfig): string {
  const safe = sanitizeProviderReplayConfig(config);
  if (!safe) return "";

  return JSON.stringify({
    baseURL: safe.baseURL,
    compatibilityMode: safe.compatibilityMode,
    decisionTransport: safe.decisionTransport,
    kind: safe.kind,
    model: safe.model,
  });
}

export function sameProviderReplayIdentity(
  left: ProviderConfig,
  right: ProviderReplayConfig,
): boolean {
  return providerReplayIdentity(left) === providerReplayIdentity(right);
}

export function providerConfigKey(config: ProviderConfig): string {
  const normalized = normalizeProviderConfig(config);
  return JSON.stringify({
    apiKey: normalized.apiKey,
    baseURL: normalized.baseURL,
    compatibilityMode: normalized.compatibilityMode,
    decisionTransport: normalized.decisionTransport,
    kind: normalized.kind,
    maxInputTokens: normalized.maxInputTokens,
    maxOutputTokens: normalized.maxOutputTokens,
    model: normalized.model,
    reasoningEffort: normalized.reasoningEffort,
    systemPrompt: normalized.systemPrompt,
    timeoutMs: normalized.timeoutMs,
  });
}
