import type { Provider } from "./types.js";

type PrismaProvider = Exclude<Provider, "hermes-agent"> | "hermes_agent";

const apiToPrismaProvider = {
  openai: "openai",
  anthropic: "anthropic",
  xai: "xai",
  gemini: "gemini",
  "hermes-agent": "hermes_agent",
} as const satisfies Record<Provider, PrismaProvider>;

const prismaToApiProvider = {
  openai: "openai",
  anthropic: "anthropic",
  xai: "xai",
  gemini: "gemini",
  hermes_agent: "hermes-agent",
  "hermes-agent": "hermes-agent",
} as const satisfies Record<PrismaProvider | "hermes-agent", Provider>;

export function toPrismaProvider(provider: Provider): PrismaProvider {
  return apiToPrismaProvider[provider];
}

export function fromPrismaProvider(provider: unknown): Provider | null {
  if (provider === null || provider === undefined) return null;
  return prismaToApiProvider[provider as keyof typeof prismaToApiProvider] ?? null;
}

export function serializeProviderFields<T extends Record<string, any>>(value: T): T {
  const next: Record<string, any> = { ...value };
  if ("initiatedProvider" in next) {
    next.initiatedProvider = fromPrismaProvider(next.initiatedProvider);
  }
  if ("lastUsedProvider" in next) {
    next.lastUsedProvider = fromPrismaProvider(next.lastUsedProvider);
  }
  if ("provider" in next) {
    next.provider = fromPrismaProvider(next.provider);
  }
  if (Array.isArray(next.calls)) {
    next.calls = next.calls.map((call: Record<string, any>) => serializeProviderFields(call));
  }
  return next as T;
}
