/**
 * Minimal non-streaming LLM inference helper using the Puter AI proxy.
 * Used by server-side renderers (diagram, icon, theme) that need a complete
 * response rather than a streaming response.
 */

const PUTER_BASE_URL = "https://api.puter.com/puterai/openai/v1";
const PUTER_DEFAULT_MODEL = "claude-3-5-haiku-20241022";
const PUTER_TOKEN_ENV = "PUTER_AUTH_TOKEN";

export interface ChatMessage {
  role: "system" | "user" | "assistant";
  content: string;
}

/**
 * Call the Puter AI proxy and return the full assistant response as a string.
 * Reads PUTER_AUTH_TOKEN from the environment (set by the board).
 *
 * Throws if the API returns a non-200 status or if PUTER_AUTH_TOKEN is not set.
 */
export async function puterChatComplete(
  messages: ChatMessage[],
  model?: string,
): Promise<string> {
  const token = process.env[PUTER_TOKEN_ENV];
  if (!token) {
    throw new Error(
      `puterChatComplete: ${PUTER_TOKEN_ENV} environment variable is not set. ` +
        "Configure the Puter auth token via the board settings.",
    );
  }

  const resolvedModel = model ?? PUTER_DEFAULT_MODEL;

  const response = await fetch(`${PUTER_BASE_URL}/chat/completions`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: resolvedModel,
      messages,
      stream: false,
    }),
  });

  if (!response.ok) {
    const text = await response.text();
    throw new Error(`Puter API error ${response.status}: ${text}`);
  }

  const data = (await response.json()) as {
    choices: Array<{ message: { content: string } }>;
  };

  const content = data.choices?.[0]?.message?.content;
  if (!content) {
    throw new Error("puterChatComplete: empty response from Puter AI");
  }

  return content;
}
