/**
 * Qdrant Vector Database Client
 *
 * Provides utilities for managing collections and vectors in Qdrant
 * for e-commerce store data synchronization.
 *
 * Vector dimensions: 3072 (OpenAI text-embedding-3-large)
 * Metric: Cosine (best for normalized embeddings)
 *
 * Connection details can be:
 * 1. Provided per-store (from stores.qdrant_url and stores.qdrant_api_key)
 * 2. Fall back to Supabase secrets (DEFAULT_QDRANT_URL, DEFAULT_QDRANT_SECRET)
 * 3. Fall back to hardcoded defaults if neither is available
 */

import { cleanHtmlContent } from './html-cleaner.ts';

// Default fallback values (used only if environment variables are not set)
const FALLBACK_QDRANT_URL = 'http://142.93.100.6:6333';
const FALLBACK_QDRANT_API_KEY = 'pyXAyyEPbLzba2RvdBwm';

const VECTOR_SIZE = 3072;
const DISTANCE_METRIC = 'Cosine'; // Best for text embeddings

/**
 * Qdrant connection configuration
 */
export interface QdrantConfig {
  url?: string;
  apiKey?: string;
}

export interface QdrantPoint {
  id: string | number;
  vector: number[];
  payload: Record<string, any>;
}

export interface CollectionSchema {
  vectors: {
    size: number;
    distance: string;
  };
  optimizers_config?: {
    indexing_threshold: number;
  };
}

/**
 * Get Qdrant connection details from environment or config
 */
function getQdrantConnection(config?: QdrantConfig): { url: string; apiKey: string } {
  // Priority order:
  // 1. Per-store config (if provided)
  // 2. Environment variables (Supabase secrets)
  // 3. Fallback constants

  const url = config?.url
    || Deno.env.get('DEFAULT_QDRANT_URL')
    || FALLBACK_QDRANT_URL;

  const apiKey = config?.apiKey
    || Deno.env.get('DEFAULT_QDRANT_SECRET')
    || FALLBACK_QDRANT_API_KEY;

  return { url, apiKey };
}

/**
 * Make a request to Qdrant API
 */
async function qdrantRequest(
  endpoint: string,
  method: string = 'GET',
  body?: any,
  config?: QdrantConfig
): Promise<any> {
  const { url: baseUrl, apiKey } = getQdrantConnection(config);
  const url = `${baseUrl}${endpoint}`;

  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
  };

  if (apiKey) {
    headers['api-key'] = apiKey;
  }

  const options: RequestInit = {
    method,
    headers,
  };

  if (body) {
    options.body = JSON.stringify(body);
  }

  const response = await fetch(url, options);

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Qdrant API error (${response.status}): ${errorText}`);
  }

  return response.json();
}

/**
 * Check if a collection exists
 */
export async function collectionExists(collectionName: string, config?: QdrantConfig): Promise<boolean> {
  try {
    await qdrantRequest(`/collections/${collectionName}`, 'GET', undefined, config);
    return true;
  } catch (error: any) {
    if (error.message?.includes('404')) {
      return false;
    }
    throw error;
  }
}

/**
 * Create a collection with optimized settings
 */
export async function createCollection(
  collectionName: string,
  payloadIndexes?: Array<{ field: string; type: string }>,
  config?: QdrantConfig
): Promise<void> {
  console.log(`[Qdrant] Creating collection: ${collectionName}`);

  const collectionConfig: any = {
    vectors: {
      size: VECTOR_SIZE,
      distance: DISTANCE_METRIC,
    },
    optimizers_config: {
      indexing_threshold: 10000, // Start indexing after 10k points
    },
    // Enable on-disk storage for large collections
    on_disk_payload: true,
  };

  await qdrantRequest(`/collections/${collectionName}`, 'PUT', collectionConfig, config);

  // Create payload indexes for faster filtering
  if (payloadIndexes && payloadIndexes.length > 0) {
    for (const index of payloadIndexes) {
      try {
        await qdrantRequest(
          `/collections/${collectionName}/index`,
          'PUT',
          {
            field_name: index.field,
            field_schema: index.type,
          },
          config
        );
        console.log(`[Qdrant] Created index on ${index.field} (${index.type})`);
      } catch (error) {
        console.error(`[Qdrant] Failed to create index on ${index.field}:`, error);
      }
    }
  }

  console.log(`[Qdrant] Collection ${collectionName} created successfully`);
}

/**
 * Delete a collection
 */
export async function deleteCollection(collectionName: string, config?: QdrantConfig): Promise<void> {
  console.log(`[Qdrant] Deleting collection: ${collectionName}`);
  await qdrantRequest(`/collections/${collectionName}`, 'DELETE', undefined, config);
  console.log(`[Qdrant] Collection ${collectionName} deleted`);
}

/**
 * Upsert points (vectors with payloads) into a collection
 */
export async function upsertPoints(
  collectionName: string,
  points: QdrantPoint[],
  config?: QdrantConfig
): Promise<void> {
  if (points.length === 0) {
    return;
  }

  console.log(`[Qdrant] Upserting ${points.length} points to ${collectionName}`);

  // Batch upsert in chunks of 100 to avoid payload size limits
  const chunkSize = 100;
  for (let i = 0; i < points.length; i += chunkSize) {
    const chunk = points.slice(i, i + chunkSize);

    await qdrantRequest(`/collections/${collectionName}/points`, 'PUT', {
      points: chunk,
    }, config);

    console.log(`[Qdrant] Upserted ${chunk.length} points (${i + chunk.length}/${points.length})`);
  }
}

/**
 * Delete points by ID
 */
export async function deletePoints(
  collectionName: string,
  pointIds: (string | number)[],
  config?: QdrantConfig
): Promise<void> {
  if (pointIds.length === 0) {
    return;
  }

  console.log(`[Qdrant] Deleting ${pointIds.length} points from ${collectionName}`);

  await qdrantRequest(`/collections/${collectionName}/points/delete`, 'POST', {
    points: pointIds,
  }, config);

  console.log(`[Qdrant] Deleted ${pointIds.length} points`);
}

/**
 * Delete points by filter
 */
export async function deletePointsByFilter(
  collectionName: string,
  filter: any,
  config?: QdrantConfig
): Promise<void> {
  console.log(`[Qdrant] Deleting points by filter from ${collectionName}`);

  await qdrantRequest(`/collections/${collectionName}/points/delete`, 'POST', {
    filter,
  }, config);

  console.log(`[Qdrant] Points deleted by filter`);
}

/**
 * Get points by IDs
 */
export async function getPoints(
  collectionName: string,
  pointIds: (string | number)[],
  config?: QdrantConfig
): Promise<any[]> {
  if (pointIds.length === 0) {
    return [];
  }

  const response = await qdrantRequest(`/collections/${collectionName}/points`, 'POST', {
    ids: pointIds,
    with_payload: true,
    with_vector: false,
  }, config);

  return response.result || [];
}

/**
 * Scroll through all points in a collection (for detecting deleted items)
 */
export async function scrollPoints(
  collectionName: string,
  filter?: any,
  limit: number = 100,
  config?: QdrantConfig
): Promise<{ points: any[]; nextOffset?: string }> {
  const body: any = {
    limit,
    with_payload: true,
    with_vector: false,
  };

  if (filter) {
    body.filter = filter;
  }

  const response = await qdrantRequest(`/collections/${collectionName}/points/scroll`, 'POST', body, config);

  return {
    points: response.result?.points || [],
    nextOffset: response.result?.next_page_offset,
  };
}

/**
 * Search for similar vectors
 */
export async function searchPoints(
  collectionName: string,
  vector: number[],
  limit: number = 10,
  filter?: any,
  config?: QdrantConfig
): Promise<any[]> {
  const body: any = {
    vector,
    limit,
    with_payload: true,
  };

  if (filter) {
    body.filter = filter;
  }

  const response = await qdrantRequest(`/collections/${collectionName}/points/search`, 'POST', body, config);

  return response.result || [];
}

/**
 * Get collection info
 */
export async function getCollectionInfo(collectionName: string, config?: QdrantConfig): Promise<any> {
  const response = await qdrantRequest(`/collections/${collectionName}`, 'GET', undefined, config);
  return response.result;
}

/**
 * Get standardized collection name for custom content
 */
export function getCustomContentCollectionName(shopname: string): string {
  // Sanitize shopname: lowercase, replace non-alphanumeric with hyphens
  const sanitized = shopname.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
  return `${sanitized}-custom-content`;
}

/**
 * Initialize custom content collection for a store
 */
export async function initializeCustomContentCollection(
  shopname: string,
  config?: QdrantConfig
): Promise<void> {
  console.log(`[Qdrant] Initializing custom content collection for store: ${shopname}`);

  const collectionName = getCustomContentCollectionName(shopname);

  if (!(await collectionExists(collectionName, config))) {
    await createCollection(collectionName, [
      { field: 'store_id', type: 'keyword' },
      { field: 'content_id', type: 'keyword' },
      { field: 'content_type', type: 'keyword' }, // 'text_entry' | 'pdf_upload'
      { field: 'title', type: 'text' },
      { field: 'chunk_index', type: 'integer' },
      { field: 'created_at', type: 'keyword' },
    ], config);
  }

  console.log(`[Qdrant] Custom content collection initialized for ${shopname}`);
}

/**
 * Sync custom content to Qdrant
 *
 * @param storeId - Store UUID
 * @param contentId - Custom content UUID
 * @param shopname - Store name for collection naming
 * @param chunks - Array of text chunks to embed
 * @param metadata - Additional metadata (title, type, filename, etc.)
 * @param config - Qdrant configuration
 * @returns Array of Qdrant point IDs for tracking
 */
export async function syncCustomContent(
  storeId: string,
  contentId: string,
  shopname: string,
  chunks: string[],
  metadata: {
    title: string;
    contentType: 'text_entry' | 'pdf_upload';
    originalFilename?: string;
    pageCount?: number;
    createdAt: string;
  },
  config?: QdrantConfig
): Promise<string[]> {
  console.log(`[Qdrant] Syncing custom content ${contentId} (${chunks.length} chunks)`);

  // Ensure collection exists
  await initializeCustomContentCollection(shopname, config);

  const collectionName = getCustomContentCollectionName(shopname);

  // Generate embeddings for all chunks
  const embeddings = await generateEmbeddingBatch(chunks);

  // Create points for each chunk
  const points: QdrantPoint[] = chunks.map((chunk, index) => {
    const pointId = generatePointId('custom-content', storeId, `${contentId}-${index}`);

    return {
      id: pointId,
      vector: embeddings[index],
      payload: {
        store_id: storeId,
        content_id: contentId,
        content_type: metadata.contentType,
        title: metadata.title,
        chunk_index: index,
        total_chunks: chunks.length,
        chunk_text: chunk,
        original_filename: metadata.originalFilename,
        page_count: metadata.pageCount,
        created_at: metadata.createdAt,
      },
    };
  });

  // Upsert points to Qdrant
  await upsertPoints(collectionName, points, config);

  console.log(`[Qdrant] Successfully synced ${points.length} chunks for content ${contentId}`);

  return points.map(p => p.id.toString());
}

/**
 * Delete custom content from Qdrant
 *
 * @param shopname - Store name for collection naming
 * @param pointIds - Array of Qdrant point IDs to delete
 * @param config - Qdrant configuration
 */
export async function deleteCustomContent(
  shopname: string,
  pointIds: string[],
  config?: QdrantConfig
): Promise<void> {
  if (pointIds.length === 0) {
    return;
  }

  console.log(`[Qdrant] Deleting ${pointIds.length} custom content points`);

  const collectionName = getCustomContentCollectionName(shopname);

  // Check if collection exists
  if (!(await collectionExists(collectionName, config))) {
    console.log(`[Qdrant] Collection ${collectionName} does not exist, nothing to delete`);
    return;
  }

  await deletePoints(collectionName, pointIds, config);

  console.log(`[Qdrant] Successfully deleted ${pointIds.length} custom content points`);
}

/**
 * Search custom content using semantic similarity
 *
 * @param shopname - Store name for collection naming
 * @param query - Search query text
 * @param limit - Maximum number of results
 * @param config - Qdrant configuration
 * @returns Array of search results with scores
 */
export async function searchCustomContent(
  shopname: string,
  query: string,
  limit: number = 5,
  config?: QdrantConfig
): Promise<Array<{
  contentId: string;
  title: string;
  contentType: string;
  chunkText: string;
  chunkIndex: number;
  totalChunks: number;
  score: number;
  originalFilename?: string;
  pageCount?: number;
}>> {
  const collectionName = getCustomContentCollectionName(shopname);

  // Check if collection exists
  if (!(await collectionExists(collectionName, config))) {
    console.log(`[Qdrant] Collection ${collectionName} does not exist`);
    return [];
  }

  // Generate query embedding
  const queryEmbedding = await generateEmbedding(query);

  // Search for similar vectors
  const results = await searchPoints(collectionName, queryEmbedding, limit, undefined, config);

  return results.map((result: any) => ({
    contentId: result.payload.content_id,
    title: result.payload.title,
    contentType: result.payload.content_type,
    chunkText: result.payload.chunk_text,
    chunkIndex: result.payload.chunk_index,
    totalChunks: result.payload.total_chunks,
    score: result.score,
    originalFilename: result.payload.original_filename,
    pageCount: result.payload.page_count,
  }));
}

/**
 * Generate a deterministic UUID from a string using a simple hash-based approach
 * This creates valid UUIDs that Qdrant accepts, while being reproducible
 */
export function generatePointId(platform: string, storeId: string, itemId: string | number): string {
  // Create a unique string identifier
  const uniqueString = `${platform}-${storeId}-${itemId}`;

  // Simple hash function (FNV-1a)
  let hash = 2166136261;
  for (let i = 0; i < uniqueString.length; i++) {
    hash ^= uniqueString.charCodeAt(i);
    hash = Math.imul(hash, 16777619);
  }

  // Convert to unsigned 32-bit and add more entropy from second pass
  const hash1 = Math.abs(hash) >>> 0;

  // Second hash for more bits
  let hash2 = 2166136261;
  for (let i = uniqueString.length - 1; i >= 0; i--) {
    hash2 ^= uniqueString.charCodeAt(i);
    hash2 = Math.imul(hash2, 16777619);
  }
  const hash2Val = Math.abs(hash2) >>> 0;

  // Generate UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  // Use hash values to create a deterministic but valid UUID
  const hex = (hash1.toString(16).padStart(8, '0') + hash2Val.toString(16).padStart(8, '0')).padStart(32, '0');

  return [
    hex.substring(0, 8),
    hex.substring(8, 12),
    '4' + hex.substring(13, 16), // Version 4
    ((parseInt(hex.substring(16, 17), 16) & 0x3) | 0x8).toString(16) + hex.substring(17, 20), // Variant
    hex.substring(20, 32)
  ].join('-');
}

/**
 * Generate standardized collection name for a store
 */
export function getCollectionName(shopname: string, dataType: 'products' | 'orders' | 'customers'): string {
  // Sanitize shopname: lowercase, replace non-alphanumeric with hyphens
  const sanitized = shopname.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
  return `${sanitized}-${dataType}`;
}

/**
 * Initialize collections for a store
 */
export async function initializeStoreCollections(
  shopname: string,
  allowOrders: boolean = true,
  allowCustomers: boolean = true,
  config?: QdrantConfig
): Promise<void> {
  console.log(`[Qdrant] Initializing collections for store: ${shopname}`);

  // Always create products collection
  const productsCollection = getCollectionName(shopname, 'products');
  if (!(await collectionExists(productsCollection, config))) {
    await createCollection(productsCollection, [
      { field: 'store_id', type: 'keyword' },
      { field: 'product_id', type: 'keyword' },
      { field: 'platform', type: 'keyword' },
      { field: 'status', type: 'keyword' },
      { field: 'price', type: 'float' },
      { field: 'sku', type: 'keyword' },
    ], config);
  }

  // Create orders collection if allowed
  if (allowOrders) {
    const ordersCollection = getCollectionName(shopname, 'orders');
    if (!(await collectionExists(ordersCollection, config))) {
      await createCollection(ordersCollection, [
        { field: 'store_id', type: 'keyword' },
        { field: 'order_id', type: 'keyword' },
        { field: 'platform', type: 'keyword' },
        { field: 'status', type: 'keyword' },
        { field: 'total_price', type: 'float' },
        { field: 'customer_email', type: 'keyword' },
        { field: 'customer_phone', type: 'keyword' },
        { field: 'billing_city', type: 'keyword' },
        { field: 'billing_country', type: 'keyword' },
        { field: 'shipping_city', type: 'keyword' },
        { field: 'shipping_country', type: 'keyword' },
      ], config);
    }
  }

  // Create customers collection if allowed
  if (allowCustomers) {
    const customersCollection = getCollectionName(shopname, 'customers');
    if (!(await collectionExists(customersCollection, config))) {
      await createCollection(customersCollection, [
        { field: 'store_id', type: 'keyword' },
        { field: 'customer_id', type: 'keyword' },
        { field: 'platform', type: 'keyword' },
        { field: 'email', type: 'keyword' },
        { field: 'phone', type: 'keyword' },
        { field: 'city', type: 'keyword' },
        { field: 'country', type: 'keyword' },
      ], config);
    }
  }

  console.log(`[Qdrant] Collections initialized for ${shopname}`);
}

/**
 * Generate embeddings using OpenRouter API with openai/text-embedding-3-large
 */
export async function generateEmbedding(text: string): Promise<number[]> {
  const OPENROUTER_API_KEY = Deno.env.get('OPENROUTER_API_KEY');

  if (!OPENROUTER_API_KEY) {
    console.error('[Qdrant] OPENROUTER_API_KEY not found, using fallback embeddings');
    return generateSimpleEmbedding(text);
  }

  try {
    // Truncate text if too long (OpenAI has a token limit)
    const truncatedText = text.substring(0, 8000); // ~8k chars ≈ 2k tokens

    const response = await fetch('https://openrouter.ai/api/v1/embeddings', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENROUTER_API_KEY}`,
        'HTTP-Referer': 'https://shopcall.ai',
        'X-Title': 'ShopCall.ai',
      },
      body: JSON.stringify({
        model: 'openai/text-embedding-3-large',
        input: truncatedText,
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`[Qdrant] OpenRouter API error (${response.status}):`, errorText);
      throw new Error(`OpenRouter API error: ${response.status}`);
    }

    const data = await response.json();

    if (data.data && data.data.length > 0 && data.data[0].embedding) {
      return data.data[0].embedding;
    } else {
      throw new Error('Invalid response format from OpenRouter API');
    }
  } catch (error: any) {
    console.error('[Qdrant] Error generating embedding:', error);
    // Fallback to simple embedding if API fails
    return generateSimpleEmbedding(text);
  }
}

/**
 * Generate embeddings for multiple texts in batch
 * More efficient than calling generateEmbedding multiple times
 */
export async function generateEmbeddingBatch(texts: string[]): Promise<number[][]> {
  const OPENROUTER_API_KEY = Deno.env.get('OPENROUTER_API_KEY');

  if (!OPENROUTER_API_KEY) {
    console.error('[Qdrant] OPENROUTER_API_KEY not found, using fallback embeddings');
    return texts.map(text => generateSimpleEmbedding(text));
  }

  if (texts.length === 0) {
    return [];
  }

  try {
    // Truncate texts if too long
    const truncatedTexts = texts.map(text => text.substring(0, 8000));

    const response = await fetch('https://openrouter.ai/api/v1/embeddings', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENROUTER_API_KEY}`,
        'HTTP-Referer': 'https://shopcall.ai',
        'X-Title': 'ShopCall.ai',
      },
      body: JSON.stringify({
        model: 'openai/text-embedding-3-large',
        input: truncatedTexts,
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`[Qdrant] OpenRouter API error (${response.status}):`, errorText);
      throw new Error(`OpenRouter API error: ${response.status}`);
    }

    const data = await response.json();

    if (data.data && Array.isArray(data.data)) {
      // Sort by index to ensure correct order
      const sorted = data.data.sort((a: any, b: any) => a.index - b.index);
      return sorted.map((item: any) => item.embedding);
    } else {
      throw new Error('Invalid response format from OpenRouter API');
    }
  } catch (error: any) {
    console.error('[Qdrant] Error generating batch embeddings:', error);
    // Fallback to simple embeddings if API fails
    return texts.map(text => generateSimpleEmbedding(text));
  }
}

/**
 * Generate a simple embedding vector (fallback when API unavailable)
 */
function generateSimpleEmbedding(text: string): number[] {
  // Fallback: generate a random normalized vector
  const vector = new Array(VECTOR_SIZE).fill(0).map(() => Math.random() - 0.5);

  // Normalize the vector
  const magnitude = Math.sqrt(vector.reduce((sum, val) => sum + val * val, 0));
  return vector.map(val => val / magnitude);
}

/**
 * Create enhanced text representation of product for embedding
 * Includes all available metadata and extra information
 */
export function createProductText(product: any): string {
  const parts: string[] = [];

  // Product title/name
  if (product.title || product.name) {
    parts.push(product.title || product.name);
  }

  // Primary description (cleaned up HTML with proper entity decoding and newline handling)
  if (product.description) {
    const desc = cleanHtmlContent(product.description);
    if (desc) {
      parts.push(desc);
    }
  }

  // Short description (WooCommerce) - only add if different from main description
  if (product.short_description && product.short_description !== product.description) {
    const shortDesc = cleanHtmlContent(product.short_description);
    if (shortDesc) {
      parts.push(shortDesc);
    }
  }

  // SKU and product identifiers
  if (product.sku) {
    parts.push(`SKU: ${product.sku}`);
  }

  // Vendor/Brand information
  if (product.vendor) {
    parts.push(`Vendor: ${product.vendor}`);
  }

  // Product type/category
  if (product.product_type) {
    parts.push(`Type: ${product.product_type}`);
  }

  // Categories (WooCommerce)
  if (product.categories && Array.isArray(product.categories)) {
    const categoryNames = product.categories
      .map((c: any) => c.name || c)
      .filter(Boolean);
    if (categoryNames.length > 0) {
      parts.push(`Categories: ${categoryNames.join(', ')}`);
    }
  }

  // Tags
  if (product.tags && Array.isArray(product.tags)) {
    const tagList = product.tags.filter(Boolean);
    if (tagList.length > 0) {
      parts.push(`Tags: ${tagList.join(', ')}`);
    }
  }

  // Variant information
  if (product.variants && Array.isArray(product.variants) && product.variants.length > 0) {
    const variantInfo: string[] = [];
    product.variants.forEach((variant: any) => {
      if (variant.title && variant.title !== 'Default Title') {
        variantInfo.push(variant.title);
      }
      if (variant.option1) variantInfo.push(variant.option1);
      if (variant.option2) variantInfo.push(variant.option2);
      if (variant.option3) variantInfo.push(variant.option3);
    });
    if (variantInfo.length > 0) {
      parts.push(`Variants: ${[...new Set(variantInfo)].join(', ')}`);
    }
  }

  // Product attributes (WooCommerce)
  if (product.attributes && Array.isArray(product.attributes)) {
    const attributes = product.attributes
      .map((attr: any) => {
        if (attr.name && attr.options) {
          const options = Array.isArray(attr.options) ? attr.options.join(', ') : attr.options;
          return `${attr.name}: ${options}`;
        }
        return null;
      })
      .filter(Boolean);
    if (attributes.length > 0) {
      parts.push(attributes.join(' | '));
    }
  }

  // Meta description (ShopRenter/SEO) - only add if different from main description
  if (product.meta_description && product.meta_description !== product.description) {
    const metaDesc = cleanHtmlContent(product.meta_description);
    if (metaDesc) {
      parts.push(metaDesc);
    }
  }

  // Price information for context
  if (product.price) {
    parts.push(`Price: ${product.price}`);
  }

  // Stock status (helpful context)
  if (product.stock_status) {
    parts.push(`Stock: ${product.stock_status}`);
  } else if (product.status) {
    parts.push(`Status: ${product.status}`);
  }

  return parts.join(' | ');
}

/**
 * Create text representation of order for embedding
 * Includes customer contact information and addresses
 */
export function createOrderText(order: any): string {
  const parts: string[] = [];

  parts.push(`Order ${order.order_number || order.name}`);

  if (order.customer_name) {
    parts.push(`Customer: ${order.customer_name}`);
  }

  // Customer email
  if (order.customer_email || order.email) {
    parts.push(`Email: ${order.customer_email || order.email}`);
  }

  // Customer phone
  if (order.customer_phone || order.phone) {
    parts.push(`Phone: ${order.customer_phone || order.phone}`);
  }

  // Billing address
  if (order.billing_address) {
    const addr = order.billing_address;
    const addressParts = [
      addr.address1,
      addr.address2,
      addr.city,
      addr.province || addr.state,
      addr.zip || addr.postcode,
      addr.country
    ].filter(Boolean);
    if (addressParts.length > 0) {
      parts.push(`Billing: ${addressParts.join(', ')}`);
    }
    if (addr.phone && addr.phone !== (order.customer_phone || order.phone)) {
      parts.push(`Billing Phone: ${addr.phone}`);
    }
  }

  // Shipping address
  if (order.shipping_address) {
    const addr = order.shipping_address;
    const addressParts = [
      addr.address1,
      addr.address2,
      addr.city,
      addr.province || addr.state,
      addr.zip || addr.postcode,
      addr.country
    ].filter(Boolean);
    if (addressParts.length > 0) {
      parts.push(`Shipping: ${addressParts.join(', ')}`);
    }
    if (addr.phone && addr.phone !== (order.customer_phone || order.phone)) {
      parts.push(`Shipping Phone: ${addr.phone}`);
    }
  }

  if (order.total_price || order.total) {
    parts.push(`Total: ${order.total_price || order.total} ${order.currency || ''}`);
  }

  if (order.financial_status || order.status) {
    parts.push(`Payment: ${order.financial_status || order.status}`);
  }

  if (order.fulfillment_status) {
    parts.push(`Fulfillment: ${order.fulfillment_status}`);
  }

  if (order.line_items && Array.isArray(order.line_items)) {
    const items = order.line_items.map((item: any) =>
      `${item.quantity || 1}x ${item.name || item.title || 'item'}`
    ).join(', ');
    parts.push(`Items: ${items}`);
  }

  // Order note
  if (order.note) {
    const note = order.note.substring(0, 200); // Limit note length
    parts.push(`Note: ${note}`);
  }

  return parts.join(' | ');
}

/**
 * Create text representation of customer for embedding
 * Includes contact information and addresses
 */
export function createCustomerText(customer: any): string {
  const parts: string[] = [];

  if (customer.first_name || customer.last_name) {
    parts.push(`${customer.first_name || ''} ${customer.last_name || ''}`.trim());
  }

  if (customer.username) {
    parts.push(`Username: ${customer.username}`);
  }

  if (customer.email) {
    parts.push(`Email: ${customer.email}`);
  }

  if (customer.phone) {
    parts.push(`Phone: ${customer.phone}`);
  }

  // Default address or billing address
  if (customer.default_address) {
    const addr = customer.default_address;
    const addressParts = [
      addr.address1,
      addr.address2,
      addr.city,
      addr.province || addr.state,
      addr.zip || addr.postcode,
      addr.country
    ].filter(Boolean);
    if (addressParts.length > 0) {
      parts.push(`Address: ${addressParts.join(', ')}`);
    }
    if (addr.phone && addr.phone !== customer.phone) {
      parts.push(`Address Phone: ${addr.phone}`);
    }
  } else if (customer.billing_address || customer.billing) {
    const addr = customer.billing_address || customer.billing;
    const addressParts = [
      addr.address1,
      addr.address2,
      addr.city,
      addr.province || addr.state,
      addr.zip || addr.postcode,
      addr.country
    ].filter(Boolean);
    if (addressParts.length > 0) {
      parts.push(`Billing: ${addressParts.join(', ')}`);
    }
    if (addr.phone && addr.phone !== customer.phone) {
      parts.push(`Billing Phone: ${addr.phone}`);
    }
  }

  // Shipping address (if different from billing)
  if (customer.shipping_address || customer.shipping) {
    const addr = customer.shipping_address || customer.shipping;
    const addressParts = [
      addr.address1,
      addr.address2,
      addr.city,
      addr.province || addr.state,
      addr.zip || addr.postcode,
      addr.country
    ].filter(Boolean);
    if (addressParts.length > 0) {
      parts.push(`Shipping: ${addressParts.join(', ')}`);
    }
    if (addr.phone && addr.phone !== customer.phone) {
      parts.push(`Shipping Phone: ${addr.phone}`);
    }
  }

  // Additional addresses (Shopify)
  if (customer.addresses && Array.isArray(customer.addresses) && customer.addresses.length > 1) {
    parts.push(`Additional addresses: ${customer.addresses.length - 1}`);
  }

  if (customer.orders_count) {
    parts.push(`Orders: ${customer.orders_count}`);
  }

  if (customer.total_spent) {
    parts.push(`Total spent: ${customer.total_spent} ${customer.currency || ''}`);
  }

  if (customer.company) {
    parts.push(`Company: ${customer.company}`);
  }

  if (customer.tags && Array.isArray(customer.tags)) {
    const tagList = customer.tags.filter(Boolean);
    if (tagList.length > 0) {
      parts.push(`Tags: ${tagList.join(', ')}`);
    }
  }

  // Customer state/status
  if (customer.state) {
    parts.push(`Status: ${customer.state}`);
  }

  // Marketing preferences
  if (customer.accepts_marketing !== undefined) {
    parts.push(`Marketing: ${customer.accepts_marketing ? 'Yes' : 'No'}`);
  }

  return parts.join(' | ');
}
