const asyncHandler = require('../middlewares/asyncHandler');
const { getFormById } = require('../repositories/formsRepository');
const { getAnswersFromImageOnePerQuestion } = require('../services/ollamaService');

/**
 * POST /api/ai/fill-from-image
 * Body: { form_id: number, image_base64: string, question_ids?: number[] }
 * Returns: { success: true, sat_answers: [{ question_id, answer_value }, ...] }
 * Uses sat_questions where ai_fill is true for the form (or question_ids if provided).
 */
exports.fillFromImage = asyncHandler(async (req, res) => {
  const { form_id, image_base64, question_ids } = req.body;

  if (!form_id || !image_base64) {
    return res.status(400).json({
      success: false,
      message: 'form_id and image_base64 are required'
    });
  }

  const form = await getFormById(form_id);
  if (!form) {
    return res.status(404).json({
      success: false,
      message: 'Form not found'
    });
  }

  const allQuestions = form.sat_questions || [];
  let questionsToFill;

  if (question_ids && Array.isArray(question_ids) && question_ids.length > 0) {
    const idSet = new Set(question_ids.map((id) => Number(id)));
    questionsToFill = allQuestions.filter((q) => idSet.has(Number(q.question_id)));
  } else {
    questionsToFill = allQuestions.filter((q) => q.ai_fill === true);
  }

  if (questionsToFill.length === 0) {
    return res.status(400).json({
      success: false,
      message: 'No sat_questions to fill. Mark sat_questions with ai_fill=1 for this form, or provide question_ids.'
    });
  }

  try {
    const sat_answers = await getAnswersFromImageOnePerQuestion(image_base64, questionsToFill);
    res.status(200).json({
      success: true,
      sat_answers
    });
  } catch (err) {
    console.error('AI fill-from-image error:', err.message);
    const message = err.message || 'AI service failed. Ensure Ollama is running (e.g. ollama serve) and the vision model is pulled (e.g. ollama pull llava).';
    res.status(503).json({
      success: false,
      message
    });
  }
});
