/**
 * Generic LLM chat completion utility.
 * Uses OPENAI_API_KEY + OPENAI_BASE_URL (OpenAI-compatible API).
 */

/**
 * Call a chat completion endpoint.
 * @param {object} options
 * @param {string} options.systemPrompt  - System prompt
 * @param {string} options.userPrompt    - User message
 * @param {string} [options.model]       - Model ID (default: gpt-4o-mini)
 * @param {number} [options.maxTokens]   - Max output tokens (default: 1024)
 * @param {number} [options.temperature] - Sampling temperature (default: 0.7)
 * @returns {Promise<string>} The assistant reply text
 */
export async function chatCompletion({ systemPrompt, userPrompt, model = 'gpt-4o-mini', maxTokens = 1024, temperature = 0.7 }) {
  const apiKey = process.env.OPENAI_API_KEY;
  if (!apiKey) throw new Error('OPENAI_API_KEY is not configured');

  const baseUrl = (process.env.OPENAI_BASE_URL || 'https://api.openai.com').replace(/\/$/, '');

  const response = await fetch(`${baseUrl}/v1/chat/completions`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      model,
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userPrompt }
      ],
      max_tokens: maxTokens,
      temperature
    })
  });

  if (!response.ok) {
    const err = await response.json().catch(() => ({}));
    throw new Error(err.error?.message || `LLM API error: ${response.status}`);
  }

  const data = await response.json();
  return data.choices?.[0]?.message?.content?.trim() || '';
}
