/**
 * Name Validation Task
 */

import { MODELS } from '../providers/groqProvider.js';
import {
  loadNameValidationPrompts,
  validateRequiredPrompts,
} from '../prompts/promptLoader.js';
import {
  buildNameUserPrompt,
  parseNameResponse,
} from '../prompts/namePrompts.js';

export const TASK_ID = 'validate.name';

export function createNameValidationTask() {
  return {
    id: TASK_ID,
    description: 'Validate product name for spelling, grammar, and conventions',

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

      if (!product?.name) {
        return { isValid: true, suggestion: null, issues: [], skipped: true, reason: 'No name 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 loadNameValidationPrompts(pool, companyKey);

        log.info('[NameValidation] Loaded prompts:', {
          hasSystem: !!prompts.system,
          systemLength: prompts.system?.length || 0,
          hasGeneral: !!prompts.general,
          generalLength: prompts.general?.length || 0,
          generalPreview: prompts.general?.substring(0, 100) || '(empty)',
          hasCompanySpecific: !!prompts.companySpecific,
          companyKey,
        });

        validateRequiredPrompts(prompts, 'name_validation');

        const userPrompt = buildNameUserPrompt(product, prompts);
        log.info('[NameValidation] User prompt:', userPrompt.substring(0, 500));

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

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

          result = parseNameResponse(response.parsed, response.content);
        } catch (jsonError) {
          if (jsonError.failedGeneration) {
            log.warn('[NameValidation] JSON mode failed, attempting to parse failed_generation:', {
              failedGeneration: jsonError.failedGeneration,
            });
            result = parseNameResponse(null, jsonError.failedGeneration);
            response = { latencyMs: 0, usage: {}, model: MODELS.SMALL };
          } else {
            log.warn('[NameValidation] JSON mode failed, retrying without JSON mode');
            response = await provider.chatCompletion({
              messages: [
                { role: 'system', content: prompts.system },
                { role: 'user', content: userPrompt },
              ],
              model: MODELS.SMALL,
              temperature: 0.2,
              maxTokens: 1500,
            });
            log.info('[NameValidation] Raw AI response (no JSON mode):', {
              parsed: response.parsed,
              content: response.content,
              contentLength: response.content?.length,
            });
            result = parseNameResponse(response.parsed, response.content);
          }
        }

        log.info(`[NameValidation] Validated "${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('[NameValidation] Error:', error.message);
        throw error;
      }
    },
  };
}
