/*
 *  author: Yagnik Poshiya
 *  organization: Webbrains Technologies Private Limited
 */

/**
 * Asks the RAG agent to test-call a project's LLM and/or embedding settings with the
 * same clients a chat turn uses (POST /v1/llm-config/validate). Server-only: the
 * request carries API keys and the internal secret.
 */

export type LlmConfigPart = { provider: string; model: string; apiKey: string };

type CheckResult = { ok: boolean; error?: string | null; dimensions?: number | null };

export type ValidateLlmConfigResult =
  | { ok: true }
  | { ok: false; message: string };

export async function validateLlmConfigViaRagAgent(input: {
  llm: LlmConfigPart | null;
  embedding: LlmConfigPart | null;
}): Promise<ValidateLlmConfigResult> {
  if (!input.llm && !input.embedding) return { ok: true };

  const base = process.env.RAG_AGENT_BASE_URL?.trim();
  const secret = process.env.RAG_AGENT_INTERNAL_SECRET?.trim();
  if (!base || !secret) {
    return { ok: false, message: 'RAG agent is not configured (RAG_AGENT_BASE_URL / RAG_AGENT_INTERNAL_SECRET).' };
  }

  const toWire = (p: LlmConfigPart | null) =>
    p ? { provider: p.provider, model: p.model, api_key: p.apiKey } : null;

  let res: Response;
  try {
    res = await fetch(`${base.replace(/\/$/, '')}/v1/llm-config/validate`, {
      method: 'POST',
      headers: { 'content-type': 'application/json', 'X-RAG-Agent-Secret': secret },
      body: JSON.stringify({ llm: toWire(input.llm), embedding: toWire(input.embedding) }),
      cache: 'no-store',
    });
  } catch {
    return { ok: false, message: 'Could not reach the RAG agent to check the API key. Try again in a moment.' };
  }
  if (!res.ok) {
    return { ok: false, message: `Could not check the API key (RAG agent returned ${res.status}).` };
  }

  const data = (await res.json().catch(() => null)) as {
    ok?: boolean;
    llm?: CheckResult | null;
    embedding?: CheckResult | null;
  } | null;
  if (!data) return { ok: false, message: 'Invalid response from the RAG agent.' };
  if (data.ok) return { ok: true };

  const problems: string[] = [];
  if (data.llm && !data.llm.ok) {
    problems.push(`LLM (${input.llm?.provider} / ${input.llm?.model}): ${data.llm.error || 'test call failed.'}`);
  }
  if (data.embedding && !data.embedding.ok) {
    problems.push(
      `Embedding (${input.embedding?.provider} / ${input.embedding?.model}): ${data.embedding.error || 'test call failed.'}`,
    );
  }
  return { ok: false, message: problems.join(' ') || 'The API key check failed.' };
}
