/**
 * Description Validation Task
 */

import { MODELS } from '../providers/groqProvider.js';
import {
  loadDescriptionValidationPrompts,
  validateRequiredPrompts,
} from '../prompts/promptLoader.js';
import {
  buildDescriptionUserPrompt,
  parseDescriptionResponse,
} from '../prompts/descriptionPrompts.js';

export const TASK_ID = 'validate.description';

export function createDescriptionValidationTask() {
  return {
    id: TASK_ID,
    description: 'Validate product description for quality and guideline compliance',

    async run(payload) {
      const { product, provider, pool, logger } = payload;
      const log = logger || console;

      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 {
        const companyKey = product.company_id || product.company_name || product.company;
        const prompts = await loadDescriptionValidationPrompts(pool, companyKey);
        validateRequiredPrompts(prompts, 'description_validation');

        const userPrompt = buildDescriptionUserPrompt(product, prompts);

        let response;
        let result;
        try {
          response = await provider.chatCompletion({
            messages: [
              { role: 'system', content: prompts.system },
              { role: 'user', content: userPrompt },
            ],
            model: MODELS.LARGE,
            temperature: 0.3,
            maxTokens: 2000,
            responseFormat: { type: 'json_object' },
          });

          log.info('[DescriptionValidation] Raw AI response:', {
            parsed: response.parsed,
            content: response.content,
            contentLength: response.content?.length,
          });

          result = parseDescriptionResponse(response.parsed, response.content);
        } catch (jsonError) {
          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 {
            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,
            });
            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;
      }
    },
  };
}
