/**
 * Mem0 Memory Proxy Edge Function
 * 
 * 提供记忆搜索 (search) 和添加 (add) 功能
 * 用于减少 Dify 侧的等待时间
 */

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
};

interface Mem0Request {
  action: 'search' | 'add';
  user_id: string;
  query?: string;           // search 时使用
  messages?: Array<{        // add 时使用
    role: 'user' | 'assistant';
    content: string;
  }>;
}

interface Mem0SearchResponse {
  results?: Array<{
    id: string;
    memory: string;
    score?: number;
  }>;
}

Deno.serve(async (req) => {
  // Handle CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  const MEM0_API_KEY = Deno.env.get('MEM0_API_KEY');
  
  if (!MEM0_API_KEY) {
    console.error('❌ MEM0_API_KEY not configured');
    return new Response(JSON.stringify({
      error: 'MEM0_API_KEY not configured',
      context: ''
    }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });
  }

  try {
    const body: Mem0Request = await req.json();
    const { action, user_id, query, messages } = body;

    console.log('📥 Mem0 Proxy Request:', { action, user_id, hasQuery: !!query, messagesCount: messages?.length });

    if (!action || !user_id) {
      return new Response(JSON.stringify({
        error: 'Missing required fields: action, user_id',
        context: ''
      }), {
        status: 400,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }

    // ========== Action: SEARCH ==========
    if (action === 'search') {
      if (!query) {
        return new Response(JSON.stringify({
          error: 'Missing query for search action',
          context: ''
        }), {
          status: 400,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

      console.log('🔍 Searching memories for user:', user_id);
      
      const searchResponse = await fetch('https://api.mem0.ai/v1/memories/search/', {
        method: 'POST',
        headers: {
          'Authorization': `Token ${MEM0_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          query: query,
          user_id: user_id,
          limit: 5  // 限制返回数量
        })
      });

      if (!searchResponse.ok) {
        const errorText = await searchResponse.text();
        console.error('❌ Mem0 search error:', searchResponse.status, errorText);
        return new Response(JSON.stringify({
          error: `Mem0 API error: ${searchResponse.status}`,
          context: ''
        }), {
          status: searchResponse.status,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

      const searchData: Mem0SearchResponse = await searchResponse.json();
      console.log('✅ Search results:', searchData.results?.length || 0, 'memories found');

      // 提取 memory 文本并拼接成上下文字符串
      const context = searchData.results
        ?.map(r => r.memory)
        .filter(Boolean)
        .join('\n') || '';

      console.log('📤 Returning context:', context.length, 'chars');

      return new Response(JSON.stringify({
        context: context,
        count: searchData.results?.length || 0
      }), {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }

    // ========== Action: ADD ==========
    if (action === 'add') {
      if (!messages || messages.length === 0) {
        return new Response(JSON.stringify({
          error: 'Missing messages for add action',
          status: 'error'
        }), {
          status: 400,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

      console.log('💾 Adding memories for user:', user_id, 'messages:', messages.length);

      const addResponse = await fetch('https://api.mem0.ai/v1/memories/', {
        method: 'POST',
        headers: {
          'Authorization': `Token ${MEM0_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: messages,
          user_id: user_id
        })
      });

      if (!addResponse.ok) {
        const errorText = await addResponse.text();
        console.error('❌ Mem0 add error:', addResponse.status, errorText);
        return new Response(JSON.stringify({
          error: `Mem0 API error: ${addResponse.status}`,
          status: 'error'
        }), {
          status: addResponse.status,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

      console.log('✅ Memories added successfully');

      return new Response(JSON.stringify({
        status: 'queued'
      }), {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }

    // Unknown action
    return new Response(JSON.stringify({
      error: `Unknown action: ${action}`,
      context: ''
    }), {
      status: 400,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });

  } catch (error) {
    console.error('❌ Mem0 Proxy error:', error);
    return new Response(JSON.stringify({
      error: (error instanceof Error ? error.message : 'Unknown error'),
      context: ''
    }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });
  }
});
