/**
 * AI Context Builder
 *
 * This module provides utilities for building AI context from store data (products, orders, customers)
 * while respecting the store_data_exclusions table. Only enabled items are included in the AI context.
 *
 * Integration with issue #46: Integrate exclusions with AI context
 */

import { SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2'

export interface AIContextOptions {
  storeId: string
  dataTypes?: ('product' | 'order' | 'customer')[]
  includeDisabled?: boolean  // Default: false
  limit?: number  // Optional limit per data type
}

export interface AIContextItem {
  data_type: 'product' | 'order' | 'customer'
  data_id: string
  is_enabled: boolean
  data: any
}

export interface AIContext {
  store_id: string
  items: AIContextItem[]
  metadata: {
    total_items: number
    by_type: {
      product?: number
      order?: number
      customer?: number
    }
    generated_at: string
  }
}

/**
 * Retrieves AI context data for a store, filtering out disabled items.
 *
 * This function:
 * 1. Fetches data from cache tables (shopify/woocommerce/shoprenter)
 * 2. LEFT JOINs with store_data_exclusions to get is_enabled status
 * 3. Applies default behavior: no exclusion record = enabled (true)
 * 4. Returns only enabled items (unless includeDisabled is true)
 *
 * @param supabase - Supabase client (should have service role key for full access)
 * @param options - Configuration options
 * @returns AI context with enabled items only
 */
export async function getAIContext(
  supabase: SupabaseClient,
  options: AIContextOptions
): Promise<AIContext> {
  const { storeId, dataTypes = ['product', 'order', 'customer'], includeDisabled = false, limit } = options

  // Get store information to determine platform
  const { data: store, error: storeError } = await supabase
    .from('stores')
    .select('id, platform_name')
    .eq('id', storeId)
    .single()

  if (storeError || !store) {
    throw new Error(`Store not found: ${storeId}`)
  }

  const platform = store.platform_name
  const items: AIContextItem[] = []
  const byType: Record<string, number> = {}

  // Process each data type
  for (const dataType of dataTypes) {
    const tableInfo = getTableInfo(platform, dataType)
    if (!tableInfo) {
      console.warn(`[AI Context] Unknown platform or data type: ${platform} / ${dataType}`)
      continue
    }

    try {
      // Fetch cache items for this data type
      let cacheQuery = supabase
        .from(tableInfo.table)
        .select('*')
        .eq('store_id', storeId)
        .order('created_at', { ascending: false })

      if (limit) {
        cacheQuery = cacheQuery.limit(limit)
      }

      const { data: cacheItems, error: cacheError } = await cacheQuery

      if (cacheError) {
        console.error(`[AI Context] Error fetching ${dataType}s from ${tableInfo.table}:`, cacheError)
        continue
      }

      if (!cacheItems || cacheItems.length === 0) {
        byType[dataType] = 0
        continue
      }

      // Get all exclusions for this store and data type
      const { data: exclusions, error: exclusionError } = await supabase
        .from('store_data_exclusions')
        .select('data_id, is_enabled')
        .eq('store_id', storeId)
        .eq('data_type', dataType)

      if (exclusionError) {
        console.error(`[AI Context] Error fetching exclusions for ${dataType}:`, exclusionError)
        // Continue with default behavior (all enabled)
      }

      // Create exclusion map for O(1) lookups
      const exclusionMap = new Map<string, boolean>()
      if (exclusions) {
        exclusions.forEach(e => {
          exclusionMap.set(e.data_id, e.is_enabled)
        })
      }

      // Process cache items and apply exclusion filter
      let enabledCount = 0
      for (const cacheItem of cacheItems) {
        const itemId = cacheItem[tableInfo.idCol]

        // Default behavior: if no exclusion record exists, treat as enabled
        const isEnabled = exclusionMap.has(itemId) ? exclusionMap.get(itemId)! : true

        // Filter based on includeDisabled option
        if (!includeDisabled && !isEnabled) {
          continue  // Skip disabled items
        }

        // Transform cache item to AI context format
        const contextItem: AIContextItem = {
          data_type: dataType,
          data_id: itemId,
          is_enabled: isEnabled,
          data: transformCacheItemToAIData(cacheItem, dataType, platform)
        }

        items.push(contextItem)
        if (isEnabled) {
          enabledCount++
        }
      }

      byType[dataType] = enabledCount
    } catch (error) {
      console.error(`[AI Context] Unexpected error processing ${dataType}:`, error)
      byType[dataType] = 0
    }
  }

  return {
    store_id: storeId,
    items,
    metadata: {
      total_items: items.filter(i => i.is_enabled).length,
      by_type: byType,
      generated_at: new Date().toISOString()
    }
  }
}

/**
 * Gets table name and ID column for a platform and data type
 */
function getTableInfo(platform: string, dataType: string): { table: string; idCol: string } | null {
  if (platform === 'woocommerce') {
    return {
      table: `woocommerce_${dataType}s_cache`,
      idCol: `wc_${dataType}_id`
    }
  } else if (platform === 'shopify') {
    return {
      table: `shopify_${dataType}s_cache`,
      idCol: `shopify_${dataType}_id`
    }
  } else if (platform === 'shoprenter') {
    return {
      table: `shoprenter_${dataType}s_cache`,
      idCol: `shoprenter_${dataType}_id`
    }
  }
  return null
}

/**
 * Transforms raw cache data into AI-friendly format
 * This extracts only the relevant fields needed for AI context
 */
function transformCacheItemToAIData(cacheItem: any, dataType: string, platform: string): any {
  if (dataType === 'product') {
    if (platform === 'shoprenter') {
      // ShopRenter stores data in product_data jsonb field
      return {
        name: cacheItem.product_data?.name || cacheItem.name,
        sku: cacheItem.product_data?.sku || cacheItem.sku,
        price: cacheItem.product_data?.price || cacheItem.price,
        currency: cacheItem.product_data?.currency || cacheItem.currency,
        description: cacheItem.product_data?.description || cacheItem.description,
        stock: cacheItem.product_data?.stock || cacheItem.stock,
        active: cacheItem.product_data?.active !== false
      }
    } else if (platform === 'shopify') {
      // Shopify has structured fields
      return {
        title: cacheItem.title,
        handle: cacheItem.handle,
        vendor: cacheItem.vendor,
        product_type: cacheItem.product_type,
        price: cacheItem.price,
        currency: cacheItem.currency,
        sku: cacheItem.sku,
        inventory_quantity: cacheItem.inventory_quantity,
        description: cacheItem.description,
        status: cacheItem.status,
        tags: cacheItem.tags
      }
    } else {
      // WooCommerce
      return {
        name: cacheItem.name,
        sku: cacheItem.sku,
        price: cacheItem.price,
        currency: cacheItem.currency,
        description: cacheItem.description,
        short_description: cacheItem.short_description,
        stock_quantity: cacheItem.stock_quantity,
        stock_status: cacheItem.stock_status,
        type: cacheItem.type,
        categories: cacheItem.categories
      }
    }
  } else if (dataType === 'order') {
    return {
      order_number: cacheItem.order_number,
      status: cacheItem.status,
      total: cacheItem.total,
      currency: cacheItem.currency,
      customer_name: cacheItem.customer_name,
      customer_email: cacheItem.customer_email,
      customer_phone: cacheItem.customer_phone,
      line_items: cacheItem.line_items,
      created_at: cacheItem.order_created_at || cacheItem.created_at
    }
  } else if (dataType === 'customer') {
    return {
      email: cacheItem.email,
      first_name: cacheItem.first_name,
      last_name: cacheItem.last_name,
      phone: cacheItem.phone,
      orders_count: cacheItem.orders_count,
      total_spent: cacheItem.total_spent
    }
  }

  return cacheItem
}

/**
 * Formats AI context as a text prompt suitable for LLM consumption
 * This is a helper function to convert structured context into natural language
 */
export function formatAIContextAsPrompt(context: AIContext): string {
  const lines: string[] = []

  lines.push('# Store Knowledge Base')
  lines.push(`Store ID: ${context.store_id}`)
  lines.push(`Total Items: ${context.metadata.total_items}`)
  lines.push('')

  // Group items by type
  const byType = new Map<string, AIContextItem[]>()
  context.items.filter(i => i.is_enabled).forEach(item => {
    if (!byType.has(item.data_type)) {
      byType.set(item.data_type, [])
    }
    byType.get(item.data_type)!.push(item)
  })

  // Format products
  if (byType.has('product')) {
    lines.push('## Products')
    byType.get('product')!.forEach(item => {
      const p = item.data
      lines.push(`- ${p.name || p.title} (${p.sku || 'no SKU'}) - ${p.currency || ''} ${p.price || 0}`)
      if (p.description) {
        lines.push(`  Description: ${p.description.substring(0, 200)}${p.description.length > 200 ? '...' : ''}`)
      }
    })
    lines.push('')
  }

  // Format orders
  if (byType.has('order')) {
    lines.push('## Recent Orders')
    byType.get('order')!.slice(0, 10).forEach(item => {
      const o = item.data
      lines.push(`- Order #${o.order_number}: ${o.customer_name} (${o.customer_email}) - ${o.currency || ''} ${o.total}`)
    })
    lines.push('')
  }

  // Format customers
  if (byType.has('customer')) {
    lines.push('## Customers')
    byType.get('customer')!.slice(0, 20).forEach(item => {
      const c = item.data
      lines.push(`- ${c.first_name} ${c.last_name} (${c.email}) - ${c.orders_count} orders, spent ${c.total_spent}`)
    })
    lines.push('')
  }

  return lines.join('\n')
}
