/**
 * Qdrant MCP Helpers
 *
 * Shared utilities for querying Qdrant from MCP tools
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { scrollPoints, searchPoints, getCollectionName, generateEmbedding, searchCustomContent } from './qdrant-client.ts';
import { LlmOrder, LlmCustomer, LlmProduct } from './mcp-types.ts';

// Initialize Supabase client
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);

/**
 * Product type for LLM output
 */
export interface LlmProduct {
  id: string;
  name: string;
  sku?: string;
  price?: string;
  currency?: string;
  status?: string;
  description?: string;
  tags?: string[];
}

/**
 * Data access policy type
 */
export type DataAccessPolicy = 'sync' | 'api_only' | 'not_allowed';

/**
 * Check if store has Qdrant sync enabled and get sync configuration
 */
export async function getStoreQdrantConfig(storeId: string): Promise<{
  enabled: boolean;
  syncProducts: boolean;
  syncOrders: boolean;
  syncCustomers: boolean;
  productsAccessPolicy: DataAccessPolicy;
  customersAccessPolicy: DataAccessPolicy;
  ordersAccessPolicy: DataAccessPolicy;
  shopname: string;
  platform: string;
} | null> {
  // Get store info
  const { data: store, error: storeError } = await supabase
    .from('stores')
    .select('store_name, platform_name, qdrant_sync_enabled')
    .eq('id', storeId)
    .single();

  if (storeError || !store) {
    console.error('[MCP Qdrant] Store not found:', storeId);
    return null;
  }

  // Get sync config with access policy columns
  const { data: syncConfig, error: syncError } = await supabase
    .from('store_sync_config')
    .select('products_access_policy, customers_access_policy, orders_access_policy')
    .eq('store_id', storeId)
    .single();

  // Default to all enabled if no config exists
  const config = syncConfig || {
    products_access_policy: 'sync' as DataAccessPolicy,
    customers_access_policy: 'sync' as DataAccessPolicy,
    orders_access_policy: 'sync' as DataAccessPolicy
  };

  // Use policy columns (default to 'sync' if not set)
  const productsPolicy = (config.products_access_policy || 'sync') as DataAccessPolicy;
  const customersPolicy = (config.customers_access_policy || 'sync') as DataAccessPolicy;
  const ordersPolicy = (config.orders_access_policy || 'sync') as DataAccessPolicy;

  return {
    enabled: store.qdrant_sync_enabled !== false, // Default to true
    syncProducts: productsPolicy === 'sync',
    syncOrders: ordersPolicy === 'sync',
    syncCustomers: customersPolicy === 'sync',
    productsAccessPolicy: productsPolicy,
    customersAccessPolicy: customersPolicy,
    ordersAccessPolicy: ordersPolicy,
    shopname: store.store_name,
    platform: store.platform_name
  };
}

/**
 * Query products from Qdrant
 */
export async function queryQdrantProducts(
  storeId: string,
  shopname: string,
  filters?: {
    sku?: string;
    name?: string;
    status?: string;
    minPrice?: number;
    maxPrice?: number;
  },
  limit: number = 20
): Promise<LlmProduct[]> {
  const collectionName = getCollectionName(shopname, 'products');

  try {
    // Build Qdrant filter
    const qdrantFilter: any = {
      must: [
        { key: 'store_id', match: { value: storeId } }
      ]
    };

    if (filters?.sku) {
      qdrantFilter.must.push({ key: 'sku', match: { value: filters.sku } });
    }

    if (filters?.status) {
      qdrantFilter.must.push({ key: 'status', match: { value: filters.status } });
    }

    if (filters?.minPrice !== undefined || filters?.maxPrice !== undefined) {
      const priceFilter: any = { key: 'price' };
      if (filters.minPrice !== undefined && filters.maxPrice !== undefined) {
        priceFilter.range = { gte: filters.minPrice, lte: filters.maxPrice };
      } else if (filters.minPrice !== undefined) {
        priceFilter.range = { gte: filters.minPrice };
      } else if (filters.maxPrice !== undefined) {
        priceFilter.range = { lte: filters.maxPrice };
      }
      qdrantFilter.must.push(priceFilter);
    }

    let products: any[];

    // Use semantic vector search if name filter is provided
    if (filters?.name) {
      console.log(`[MCP Qdrant] Using semantic search for product name: "${filters.name}"`);

      // Generate embedding for the search query
      const embedding = await generateEmbedding(filters.name);

      // Use searchPoints for semantic similarity search
      const searchResults = await searchPoints(
        collectionName,
        embedding,
        limit,
        qdrantFilter
      );

      // Extract payloads from search results
      products = searchResults.map((result: any) => result.payload);

      console.log(`[MCP Qdrant] Semantic search found ${products.length} products`);
    } else {
      // Use scroll-based search for other filters
      console.log('[MCP Qdrant] Using scroll-based search');
      const result = await scrollPoints(collectionName, qdrantFilter, limit);
      products = result.points.map((point: any) => point.payload).slice(0, limit);
    }

    // Format for LLM
    return products.map((p: any) => formatProductForLlm(p));
  } catch (error) {
    console.error('[MCP Qdrant] Error querying products:', error);
    throw error;
  }
}

/**
 * Query orders from Qdrant
 */
export async function queryQdrantOrders(
  storeId: string,
  shopname: string,
  filters?: {
    email?: string;
    status?: string;
    minTotal?: number;
    maxTotal?: number;
  },
  limit: number = 20
): Promise<LlmOrder[]> {
  const collectionName = getCollectionName(shopname, 'orders');

  try {
    // Build Qdrant filter
    const qdrantFilter: any = {
      must: [
        { key: 'store_id', match: { value: storeId } }
      ]
    };

    if (filters?.email) {
      qdrantFilter.must.push({ key: 'customer_email', match: { value: filters.email } });
    }

    if (filters?.status) {
      qdrantFilter.must.push({ key: 'status', match: { value: filters.status } });
    }

    if (filters?.minTotal !== undefined || filters?.maxTotal !== undefined) {
      const totalFilter: any = { key: 'total_price' };
      if (filters.minTotal !== undefined && filters.maxTotal !== undefined) {
        totalFilter.range = { gte: filters.minTotal, lte: filters.maxTotal };
      } else if (filters.minTotal !== undefined) {
        totalFilter.range = { gte: filters.minTotal };
      } else if (filters.maxTotal !== undefined) {
        totalFilter.range = { lte: filters.maxTotal };
      }
      qdrantFilter.must.push(totalFilter);
    }

    // Scroll through points
    const result = await scrollPoints(collectionName, qdrantFilter, limit);

    const orders = result.points.map((point: any) => point.payload).slice(0, limit);

    // Format for LLM
    return orders.map((o: any) => formatOrderForLlm(o));
  } catch (error) {
    console.error('[MCP Qdrant] Error querying orders:', error);
    throw error;
  }
}

/**
 * Query customers from Qdrant
 */
export async function queryQdrantCustomers(
  storeId: string,
  shopname: string,
  filters?: {
    email?: string;
    phone?: string;
  },
  limit: number = 20
): Promise<LlmCustomer[]> {
  const collectionName = getCollectionName(shopname, 'customers');

  try {
    // Build Qdrant filter
    const qdrantFilter: any = {
      must: [
        { key: 'store_id', match: { value: storeId } }
      ]
    };

    if (filters?.email) {
      qdrantFilter.must.push({ key: 'email', match: { value: filters.email } });
    }

    if (filters?.phone) {
      qdrantFilter.must.push({ key: 'phone', match: { value: filters.phone } });
    }

    // Scroll through points
    const result = await scrollPoints(collectionName, qdrantFilter, limit);

    const customers = result.points.map((point: any) => point.payload).slice(0, limit);

    // Format for LLM
    return customers.map((c: any) => formatCustomerForLlm(c));
  } catch (error) {
    console.error('[MCP Qdrant] Error querying customers:', error);
    throw error;
  }
}

/**
 * Format product from Qdrant payload to LLM-friendly format
 */
function formatProductForLlm(product: any): LlmProduct {
  return {
    id: product.product_id || product.id,
    name: product.name || product.title,
    sku: product.sku || undefined,
    price: product.price ? product.price.toString() : undefined,
    currency: product.currency || undefined,
    status: product.status || undefined,
    description: product.description || undefined,
    tags: product.tags || undefined
  };
}

/**
 * Format order from Qdrant payload to LLM-friendly format
 */
function formatOrderForLlm(order: any): LlmOrder {
  return {
    id: order.order_id || order.id,
    orderNumber: order.order_number || order.name,
    customer: {
      name: order.customer_name || 'Unknown',
      email: order.customer_email || order.email || '',
      phone: order.customer_phone || order.phone || undefined
    },
    status: order.status || order.financial_status || 'unknown',
    total: order.total || order.total_price || '0',
    currency: order.currency || undefined,
    items: order.line_items || order.items || [],
    createdAt: order.created_at || order.order_created_at || new Date().toISOString()
  };
}

/**
 * Format customer from Qdrant payload to LLM-friendly format
 */
function formatCustomerForLlm(customer: any): LlmCustomer {
  return {
    id: customer.customer_id || customer.id,
    name: `${customer.first_name || ''} ${customer.last_name || ''}`.trim() || 'Unknown',
    email: customer.email || '',
    phone: customer.phone || undefined,
    ordersCount: customer.orders_count || undefined,
    totalSpent: customer.total_spent ? customer.total_spent.toString() : undefined
  };
}

/**
 * Custom content result for LLM
 */
export interface LlmCustomContent {
  id: string;
  title: string;
  contentType: 'text_entry' | 'pdf_upload';
  excerpt: string;
  chunkIndex: number;
  totalChunks: number;
  relevanceScore: number;
  originalFilename?: string;
  pageCount?: number;
}

/**
 * Query custom content from Qdrant
 *
 * @param storeId - Store UUID
 * @param shopname - Store name for collection naming
 * @param query - Search query text
 * @param limit - Maximum number of results
 * @returns Array of custom content results
 */
export async function queryQdrantCustomContent(
  storeId: string,
  shopname: string,
  query: string,
  limit: number = 5
): Promise<LlmCustomContent[]> {
  try {
    console.log(`[MCP Qdrant] Searching custom content for: "${query}"`);

    // Use semantic search from qdrant-client
    const results = await searchCustomContent(shopname, query, limit);

    console.log(`[MCP Qdrant] Found ${results.length} custom content results`);

    // Format for LLM
    return results.map((result) => ({
      id: result.contentId,
      title: result.title,
      contentType: result.contentType as 'text_entry' | 'pdf_upload',
      excerpt: truncateText(result.chunkText, 500),
      chunkIndex: result.chunkIndex,
      totalChunks: result.totalChunks,
      relevanceScore: result.score,
      originalFilename: result.originalFilename,
      pageCount: result.pageCount,
    }));
  } catch (error) {
    console.error('[MCP Qdrant] Error querying custom content:', error);
    throw error;
  }
}

/**
 * Truncate text to a maximum length
 */
function truncateText(text: string, maxLength: number): string {
  if (text.length <= maxLength) {
    return text;
  }
  return text.substring(0, maxLength) + '...';
}
