import { Langfuse } from "langfuse";

let client: Langfuse | null = null;

function isTruthy(value: string | undefined) {
  const v = (value ?? "").trim().toLowerCase();
  return v === "1" || v === "true" || v === "yes" || v === "on";
}

export function isLangfuseEnabled() {
  const enabledRaw = process.env.LANGFUSE_ENABLED;
  if (enabledRaw && !isTruthy(enabledRaw)) return false;
  return Boolean((process.env.LANGFUSE_PUBLIC_KEY ?? "").trim() && (process.env.LANGFUSE_SECRET_KEY ?? "").trim());
}

export function getLangfuseClient() {
  if (!isLangfuseEnabled()) return null;
  if (client) return client;

  client = new Langfuse({
    publicKey: (process.env.LANGFUSE_PUBLIC_KEY ?? "").trim(),
    secretKey: (process.env.LANGFUSE_SECRET_KEY ?? "").trim(),
    baseUrl: (process.env.LANGFUSE_BASE_URL ?? "http://langfuse-web:3000").trim(),
    enabled: true,
  });

  return client;
}

