/**
 * AI Validation utility functions
 *
 * Helper functions for processing AI validation data and managing progress
 */

import type { Fields } from '@/components/product-import/types';

/**
 * Clean data for AI validation by including all fields
 *
 * Ensures every field is present in the data sent to the API,
 * converting undefined values to empty strings
 */
export function prepareDataForAiValidation<T extends string>(
  data: any[],
  fields: Fields<T>
): Record<string, any>[] {
  return data.map(item => {
    const { __index, __aiSupplemental, ...rest } = item as Record<string, any>;
    const withAllKeys: Record<string, any> = {};

    fields.forEach((f) => {
      const k = String(f.key);
      if (Array.isArray(rest[k])) {
        withAllKeys[k] = rest[k];
      } else if (rest[k] === undefined) {
        withAllKeys[k] = "";
      } else {
        withAllKeys[k] = rest[k];
      }
    });

    if (typeof __aiSupplemental === 'object' && __aiSupplemental !== null) {
      withAllKeys.aiSupplementalInfo = __aiSupplemental;
    }

    return withAllKeys;
  });
}

/**
 * Process AI-corrected data to handle multi-select and select fields
 *
 * Converts comma-separated strings to arrays for multi-select fields
 * and handles label-to-value conversions for select fields
 */
export function processAiCorrectedData<T extends string>(
  correctedData: any[],
  originalData: any[],
  fields: Fields<T>
): any[] {
  return correctedData.map((corrected: any, index: number) => {
    // Start with original data to preserve metadata like __index
    const original = originalData[index] || {};
    const processed = { ...original, ...corrected };

    // Process each field according to its type
    Object.keys(processed).forEach(key => {
      if (key.startsWith('__')) return; // Skip metadata fields

      const fieldConfig = fields.find(f => String(f.key) === key);
      if (!fieldConfig) return;

      // Handle multi-select fields (comma-separated values → array)
      if (fieldConfig?.fieldType.type === 'multi-select' && typeof processed[key] === 'string') {
        processed[key] = processed[key]
          .split(',')
          .map((v: string) => v.trim())
          .filter(Boolean);
      }
    });

    return processed;
  });
}

/**
 * Calculate progress percentage based on elapsed time and estimates
 *
 * @param step - Current step number (1-5)
 * @param elapsedSeconds - Time elapsed since start
 * @param estimatedSeconds - Estimated total time (optional)
 * @returns Progress percentage (0-95, never reaches 100 until complete)
 */
export function calculateProgressPercent(
  step: number,
  elapsedSeconds: number,
  estimatedSeconds?: number
): number {
  if (estimatedSeconds && estimatedSeconds > 0) {
    // Time-based progress
    return Math.min(95, (elapsedSeconds / estimatedSeconds) * 100);
  }

  // Step-based progress with time adjustment
  const baseProgress = (step / 5) * 100;
  const timeAdjustment = step === 1 ? Math.min(20, elapsedSeconds * 0.5) : 0;
  return Math.min(95, baseProgress + timeAdjustment);
}

/**
 * Extract base status message by removing time information
 *
 * Removes patterns like "(5s remaining)" or "(1m 30s elapsed)"
 */
export function extractBaseStatus(status: string): string {
  return status
    .replace(/\s\(\d+[ms].+\)$/, '')
    .replace(/\s\(\d+m \d+s.+\)$/, '');
}
