/**
 * Mem0 Memory Client
 * 
 * 实现"三明治架构"：
 * 1. 先查记忆 (search) - 带1秒超时
 * 2. 再问 AI (Dify)
 * 3. 最后存记忆 (add) - 静默异步
 */

import { supabase } from '@/integrations/supabase/client';

interface SearchResult {
  context: string;
  count: number;
}

interface AddResult {
  status: 'queued' | 'error';
}

/**
 * 搜索用户记忆
 * 带1秒超时限制，超时或报错返回空字符串
 */
export async function searchMemory(userId: string, query: string): Promise<string> {
  const TIMEOUT_MS = 1000; // 1秒超时

  try {
    const searchPromise = supabase.functions.invoke<SearchResult>('mem0-proxy', {
      body: {
        action: 'search',
        user_id: userId,
        query: query
      }
    });

    const timeoutPromise = new Promise<never>((_, reject) => {
      setTimeout(() => reject(new Error('Mem0 search timeout')), TIMEOUT_MS);
    });

    const { data, error } = await Promise.race([searchPromise, timeoutPromise]);

    if (error) {
      console.warn('⚠️ Mem0 search error:', error);
      return '';
    }

    console.log('🧠 Mem0 search result:', data?.count || 0, 'memories found');
    return data?.context || '';
  } catch (e) {
    // 超时或其他错误，静默返回空字符串
    console.warn('⚠️ Mem0 search failed (timeout or error):', e instanceof Error ? e.message : e);
    return '';
  }
}

/**
 * 添加对话到记忆
 * 静默异步，不阻塞主流程
 */
export function addMemory(
  userId: string, 
  userContent: string, 
  assistantContent: string
): void {
  // 使用 void 确保不等待
  void (async () => {
    try {
      const messages = [
        { role: 'user' as const, content: userContent },
        { role: 'assistant' as const, content: assistantContent }
      ];

      console.log('💾 Mem0 adding memory for user:', userId);

      const { error } = await supabase.functions.invoke<AddResult>('mem0-proxy', {
        body: {
          action: 'add',
          user_id: userId,
          messages: messages
        }
      });

      if (error) {
        console.warn('⚠️ Mem0 add error:', error);
      } else {
        console.log('✅ Mem0 memory queued');
      }
    } catch (e) {
      // 静默失败，不影响用户体验
      console.warn('⚠️ Mem0 add failed:', e instanceof Error ? e.message : e);
    }
  })();
}
