import openai from '../external-services/openai.js';
import query from '../server-utils/query.js';
import { createEmbedding } from '../utils/semanticSearch.js';

const NUM_QUESTIONS = 5;
const NUM_ATTEMPTS = 5;

const PRE_PROMPT = `
  I'm creating a database of questions and answers to help users of a
  digital audio workstation called WavTool. A snippet of documentation
  will follow this paragraph. To help with search indexing, compose
  ${NUM_QUESTIONS} succinct questions a user might ask which this snippet
  would help answer.
`
  .split('\n')
  .map((x) => x.trim())
  .filter((x) => x.length > 0)
  .join(' ');

const createQuestions = async (answer) => {
  for (let i = 0; i < NUM_ATTEMPTS; i++) {
    const res = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [
        { role: 'system', content: '' },
        { role: 'user', content: `${PRE_PROMPT}\n\n${answer}` },
      ],
    });
    const qs = res.choices[0].message.content
      .split('\n')
      .map((x) => x.replace(/.../, '').trim())
      .filter((x) => x.length > 0);
    if (qs.length === NUM_QUESTIONS) {
      return qs;
    }
  }
  throw new Error(`Repeatedly failed to create questions for answer ${answer}`);
};

const arrayToPgVector = (arr) => {
  return `[${arr.join(',')}]`;
};

export const UpdateFAQData = async () => {
  const answersMissingQuestions = await query(
    `SELECT id, answer FROM faq_answers a WHERE (SELECT COUNT(1) FROM faq_questions WHERE answer_id = a.id) < $1`,
    [NUM_QUESTIONS]
  );
  for (const answer of answersMissingQuestions.rows) {
    const questions = await createQuestions(answer.answer);
    for (const question of questions) {
      await query(`INSERT INTO faq_questions (answer_id, question) VALUES ($1, $2)`, [answer.id, question]);
    }
  }

  const questionsMissingEmbeddings = await query(`SELECT id, question FROM faq_questions WHERE embedding IS NULL`, []);
  for (const question of questionsMissingEmbeddings.rows) {
    const embedding = await createEmbedding(question.question);
    await query(`UPDATE faq_questions SET embedding = $1 WHERE id = $2`, [arrayToPgVector(embedding), question.id]);
  }
};

await UpdateFAQData();
