/**
 * Description Validation Task
 *
 * Validates a product description for quality, accuracy, and guideline compliance.
 * Uses Groq with the larger model for better reasoning about content quality.
 * Loads all prompts from the database (no hardcoded prompts).
 */

const { MODELS } = require('../providers/groqProvider');
const {
  loadDescriptionValidationPrompts,
  validateRequiredPrompts
} = require('../prompts/promptLoader');
const {
  buildDescriptionUserPrompt,
  parseDescriptionResponse
} = require('../prompts/descriptionPrompts');

const TASK_ID = 'validate.description';

/**
 * Create the description validation task
 *
 * @returns {Object} Task definition
 */
function createDescriptionValidationTask() {
  return {
    id: TASK_ID,
    description: 'Validate product description for quality and guideline compliance',

    /**
     * Run the description validation
     *
     * @param {Object} payload
     * @param {Object} payload.product - Product data
     * @param {string} payload.product.name - Product name (for context)
     * @param {string} payload.product.description - Description to validate
     * @param {string} [payload.product.company_name] - Company name
     * @param {string} [payload.product.company_id] - Company ID for loading specific rules
     * @param {string} [payload.product.categories] - Product categories
     * @param {Object} payload.provider - Groq provider instance
     * @param {Object} payload.pool - PostgreSQL pool
     * @param {Object} [payload.logger] - Logger instance
     * @returns {Promise<Object>}
     */
    async run(payload) {
      const { product, provider, pool, logger } = payload;
      const log = logger || console;

      // Validate required input
      if (!product?.name && !product?.description) {
        return {
          isValid: true,
          suggestion: null,
          issues: [],
          skipped: true,
          reason: 'No name or description provided'
        };
      }

      if (!provider) {
        throw new Error('Groq provider not available');
      }

      if (!pool) {
        throw new Error('Database pool not available');
      }

      try {
        // Load prompts from database
        const companyKey = product.company_id || product.company_name || product.company;
        const prompts = await loadDescriptionValidationPrompts(pool, companyKey);

        // Validate required prompts exist
        validateRequiredPrompts(prompts, 'description_validation');

        // Build the user prompt with database-loaded prompts
        const userPrompt = buildDescriptionUserPrompt(product, prompts);

        let response;
        let result;

        try {
          // Try with JSON mode first
          response = await provider.chatCompletion({
            messages: [
              { role: 'system', content: prompts.system },
              { role: 'user', content: userPrompt }
            ],
            model: MODELS.LARGE,  // openai/gpt-oss-120b - better for content analysis
            temperature: 0.3,     // Slightly higher for creative suggestions
            maxTokens: 2000,      // Reasoning models need extra tokens for thinking
            responseFormat: { type: 'json_object' }
          });

          // Log full raw response for debugging
          log.info('[DescriptionValidation] Raw AI response:', {
            parsed: response.parsed,
            content: response.content,
            contentLength: response.content?.length
          });

          // Parse the response
          result = parseDescriptionResponse(response.parsed, response.content);
        } catch (jsonError) {
          // If JSON mode failed, check if we have failedGeneration to parse
          if (jsonError.failedGeneration) {
            log.warn('[DescriptionValidation] JSON mode failed, attempting to parse failed_generation:', {
              failedGeneration: jsonError.failedGeneration
            });
            result = parseDescriptionResponse(null, jsonError.failedGeneration);
            response = { latencyMs: 0, usage: {}, model: MODELS.LARGE };
          } else {
            // Retry without JSON mode
            log.warn('[DescriptionValidation] JSON mode failed, retrying without JSON mode');
            response = await provider.chatCompletion({
              messages: [
                { role: 'system', content: prompts.system },
                { role: 'user', content: userPrompt }
              ],
              model: MODELS.LARGE,
              temperature: 0.3,
              maxTokens: 2000  // Reasoning models need extra tokens for thinking
              // No responseFormat - let the model respond freely
            });
            log.info('[DescriptionValidation] Raw AI response (no JSON mode):', {
              parsed: response.parsed,
              content: response.content,
              contentLength: response.content?.length
            });
            result = parseDescriptionResponse(response.parsed, response.content);
          }
        }

        log.info(`[DescriptionValidation] Validated description for "${product.name}" in ${response.latencyMs}ms`, {
          isValid: result.isValid,
          hasSuggestion: !!result.suggestion,
          issueCount: result.issues.length
        });

        return {
          ...result,
          latencyMs: response.latencyMs,
          usage: response.usage,
          model: response.model
        };
      } catch (error) {
        log.error('[DescriptionValidation] Error:', error.message);
        throw error;
      }
    }
  };
}

module.exports = {
  TASK_ID,
  createDescriptionValidationTask
};
