/**
 * lib/openai-client.js — lazily-constructed OpenAI clients.
 * Owns: OpenAI SDK instantiation and the "is AI configured?" predicate.
 * Does NOT own: prompt construction, model choice, or any AI_ENABLED gating at call sites.
 *
 * WHY THIS EXISTS — do not go back to a module-scope `new OpenAI({...})`:
 * the SDK constructor THROWS ("The OPENAI_API_KEY environment variable is missing
 * or empty") when no key is present, even when apiKey is passed explicitly as
 * undefined. Constructing at module scope therefore crashed the process at
 * require() time on any install without a key — which made server.js's own
 * AI_ENABLED guard unreachable dead code, since line ~119 threw long before it.
 * OpenAI is documented as OPTIONAL (self-hosted installs run health checks with
 * an AI placeholder), so boot must never depend on the key being set.
 *
 * Clients are cached per (timeout, maxRetries) so each call site keeps the exact
 * timeout it had before, without creating a client per request.
 */

'use strict';

const OpenAI = require('openai');

/** True when an API key is configured. Call sites gate on this BEFORE getOpenAI(). */
const AI_ENABLED = !!process.env.OPENAI_API_KEY;

const AI_UNAVAILABLE_MSG = 'AI analysis unavailable — no API key configured';

const clients = new Map();

/**
 * Get a cached OpenAI client, constructing it on first use.
 *
 * Throws if OPENAI_API_KEY is unset — callers must check AI_ENABLED first and
 * degrade gracefully. Throwing here (rather than returning a dud client) keeps a
 * misconfiguration loud at the point of use instead of surfacing as an opaque
 * 401 from the API.
 *
 * @param {object} [opts]
 * @param {number} [opts.timeout]     - request timeout in ms; omit for the SDK default
 * @param {number} [opts.maxRetries]  - retry count; defaults to 0 (matches every existing call site)
 * @returns {OpenAI}
 */
function getOpenAI({ timeout, maxRetries = 0 } = {}) {
  if (!process.env.OPENAI_API_KEY) {
    throw new Error(AI_UNAVAILABLE_MSG);
  }

  const cacheKey = `${timeout ?? 'default'}:${maxRetries}`;
  if (!clients.has(cacheKey)) {
    const config = {
      apiKey: process.env.OPENAI_API_KEY,
      baseURL: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1',
      maxRetries,
    };
    if (timeout !== undefined) config.timeout = timeout;
    clients.set(cacheKey, new OpenAI(config));
  }
  return clients.get(cacheKey);
}

module.exports = { getOpenAI, AI_ENABLED, AI_UNAVAILABLE_MSG };
