/**
 * Build the prompt text to send to OpenAI.
 * This module does not call OpenAI or perform any search logic.
 * @param {string} question - The user's question.
 * @param {string|Array|Object} knowledge - The knowledge content to include in the prompt.
 * @returns {string}
 */
function buildPrompt(question, knowledge) {
  if (typeof question !== 'string') {
    throw new TypeError('question must be a string');
  }

  const formattedKnowledge = formatKnowledge(knowledge);

  return `You are GNR AI, the official AI assistant of GNR Soft Tech.

Rules:
- Answer ONLY from the provided knowledge.
- Never mention markdown files.
- Never mention filenames.
- Never invent prices.
- Never invent services.
- If information is missing, politely say you don't know.
- Reply professionally.
- Format using Markdown.

Knowledge:
${formattedKnowledge}

User Question:
${question}`;
}

/**
 * Convert the knowledge input into a single string representation.
 * @param {string|Array|Object} knowledge
 * @returns {string}
 */
function formatKnowledge(knowledge) {
  if (typeof knowledge === 'string') {
    return knowledge.trim();
  }

  if (Array.isArray(knowledge)) {
    return knowledge
      .map((item) => {
        if (typeof item === 'string') {
          return item.trim();
        }

        if (item && typeof item.content === 'string') {
          return item.content.trim();
        }

        return '';
      })
      .filter(Boolean)
      .join('\n\n');
  }

  if (knowledge && typeof knowledge.content === 'string') {
    return knowledge.content.trim();
  }

  return '';
}

module.exports = {
  buildPrompt
};
