/**
 * useAiApi - AI Validation API Calls
 *
 * Handles all API communication for AI validation.
 */

import config from '@/config';
import { apiFetch } from '@/utils/api';
import type { RowData } from '../../store/types';
import type { Field } from '../../../../types';
import { prepareDataForAiValidation } from '../../utils/aiValidationUtils';

export interface AiValidationRequest {
  products: Record<string, unknown>[];
  aiSupplementalColumns: string[];
  options?: {
    batchSize?: number;
    temperature?: number;
  };
}

/**
 * Token usage from AI validation with all metrics
 */
export interface AiTokenUsage {
  prompt: number | null;
  completion: number | null;
  total: number | null;
  reasoning?: number | null;
  cachedPrompt?: number | null;
}

export interface AiValidationResponse {
  success: boolean;
  results?: {
    products: Record<string, unknown>[];
    changes: Array<{
      productIndex: number;
      fieldKey: string;
      originalValue: unknown;
      correctedValue: unknown;
      confidence?: number;
    }>;
    tokenUsage?: AiTokenUsage;
  };
  // Top-level fields from AI response
  correctedData?: Record<string, unknown>[];
  changes?: string[]; // Human-readable change summaries
  changeDetails?: Array<{
    productIndex: number;
    fieldKey: string;
    originalValue: unknown;
    correctedValue: unknown;
    confidence?: number;
  }>;
  warnings?: string[];
  summary?: string;
  model?: string;
  reasoningEffort?: string;
  tokenUsage?: AiTokenUsage;
  performanceMetrics?: {
    model?: string;
    reasoningEffort?: string;
    tokenUsage?: AiTokenUsage;
    processingTimeSeconds?: number;
    promptLength?: number;
  };
  error?: string;
}

export interface TaxonomyStats {
  categories: number;
  themes: number;
  colors: number;
  taxCodes: number;
  sizeCategories: number;
  suppliers: number;
  companies: number;
  artists: number;
}

export interface AiDebugPromptResponse {
  prompt?: string;
  basePrompt?: string;
  sampleFullPrompt?: string;
  promptLength?: number;
  estimatedTokens?: number;
  taxonomyStats?: TaxonomyStats;
  apiFormat?: Array<{ role: string; content: string }>;
  promptSources?: {
    systemPrompt?: { id: number; prompt_text: string };
    generalPrompt?: { id: number; prompt_text: string };
    companyPrompts?: Array<{
      id: number;
      company: string;
      companyName?: string;
      prompt_text: string;
    }>;
  };
  estimatedProcessingTime?: {
    seconds: number | null;
    sampleCount: number;
  };
}

/**
 * Prepare products data for AI validation
 *
 * Uses the shared utility function to prepare data, ensuring all fields are present
 * and converting undefined values to empty strings. Also adds index tracking and
 * handles AI supplemental columns.
 */
export const prepareProductsForAi = (
  rows: RowData[],
  fields: Field<string>[]
): Record<string, unknown>[] => {
  // Add __index metadata for tracking
  const rowsWithIndex = rows.map((row, index) => ({
    ...row,
    __index: index,
  }));

  // Use the shared utility function for base preparation
  const prepared = prepareDataForAiValidation(rowsWithIndex, fields as any);

  // Add supplemental columns with different naming to distinguish from regular fields
  return prepared.map((product, index) => {
    const row = rows[index];

    // Add _index for change tracking
    product._index = index;

    // Add supplemental columns as _supplemental_ prefixed keys
    if (row.__aiSupplemental && Array.isArray(row.__aiSupplemental)) {
      row.__aiSupplemental.forEach((col) => {
        if (row[col] !== undefined) {
          product[`_supplemental_${col}`] = row[col];
        }
      });
    }

    return product;
  });
};

/**
 * Extract AI supplemental columns from rows
 */
export const extractAiSupplementalColumns = (rows: RowData[]): string[] => {
  const columns = new Set<string>();

  rows.forEach((row) => {
    if (row.__aiSupplemental && Array.isArray(row.__aiSupplemental)) {
      row.__aiSupplemental.forEach((col) => columns.add(col));
    }
  });

  return Array.from(columns);
};

/**
 * Run AI validation on products
 */
export const runAiValidation = async (
  request: AiValidationRequest
): Promise<AiValidationResponse> => {
  try {
    const response = await apiFetch(`${config.apiUrl}/ai-validation/validate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.error || `API error (${response.status})`);
    }

    return await response.json();
  } catch (error) {
    console.error('AI validation API error:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
};

/**
 * Get AI debug prompt (for preview or time estimation)
 * @param products - Products to include in the prompt
 * @param aiSupplementalColumns - Supplemental columns to include
 * @param options.previewOnly - If true, only send first 5 products for preview
 */
export const getAiDebugPrompt = async (
  products: Record<string, unknown>[],
  aiSupplementalColumns: string[],
  options?: { previewOnly?: boolean }
): Promise<AiDebugPromptResponse | null> => {
  try {
    // For preview dialog, only send first 5 products
    // For time estimation before validation, send all products
    const productsToSend = options?.previewOnly ? products.slice(0, 5) : products;

    const response = await apiFetch(`${config.apiUrl}/ai-validation/debug`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        products: productsToSend,
        aiSupplementalColumns,
      }),
    });

    if (!response.ok) {
      throw new Error(`API error (${response.status})`);
    }

    return await response.json();
  } catch (error) {
    console.error('AI debug prompt error:', error);
    return null;
  }
};

/**
 * Get time estimation for AI validation
 * Fetches from debug endpoint with all products to get accurate estimate
 */
export const getAiTimeEstimate = async (
  products: Record<string, unknown>[],
  aiSupplementalColumns: string[]
): Promise<{ estimatedSeconds: number | null; promptLength: number | null }> => {
  try {
    const debugData = await getAiDebugPrompt(products, aiSupplementalColumns, { previewOnly: false });

    return {
      estimatedSeconds: debugData?.estimatedProcessingTime?.seconds ?? null,
      promptLength: debugData?.promptLength ?? null,
    };
  } catch (error) {
    console.error('Error getting time estimate:', error);
    return { estimatedSeconds: null, promptLength: null };
  }
};
