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

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

export function toPrismaProvider(provider: Provider): PrismaProvider {
  return provider === "hermes-agent" ? "hermes_agent" : provider;
}

export function fromPrismaProvider(provider: unknown): Provider | null {
  if (provider === null || provider === undefined) return null;
  if (provider === "hermes_agent" || provider === "hermes-agent") return "hermes-agent";
  if (provider === "openai" || provider === "anthropic" || provider === "xai") return provider;
  return 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;
}
