/**
 * Consumer Chat Edge Function Client
 * C端消费者聊天 - 统一调用入口
 *
 * 注意：callCozeEdge 是历史兼容名称；当前优先走 dify-chat-stream。
 */

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

const SUPABASE_URL = import.meta.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;

interface CozeRequestOptions {
  message: string;
  userId: string;
  conversationId?: string;
  userContext?: string;  // Mem0 记忆上下文
  product?: {
    id: string;
    title: string;
    description?: string;
    price?: number;
  };
  catalog?: Array<{
    id: string;
    name: string;
    price: number;
    stock_quantity?: number;
    category?: string;
    description?: string;
  }>;
}

interface CozeResponse {
  title: string;
  intent: "SHOPPING" | "AFTERSALES" | "GENERAL" | "COMPARE" | "SEARCH" | string;
  sentiment: "POSITIVE" | "NEUTRAL" | "NEGATIVE";
  highlights: string[];
  picks: Array<{
    product_id: string;
    note: string;
    source?: string;
  }>;
  comparison?: string;
  next: string[];
  meta: {
    platform: string;
    user: string;
    catalog_count: number;
    probe_id: string;
  };
  error?: string;
  trace_id?: string;
  conversation_id?: string;
  answer?: string;
}

type StreamDonePayload = Partial<CozeResponse> & {
  type?: 'done';
};

function processDifyStreamLine(line: string, state: { fullContent: string; doneData: StreamDonePayload | null }) {
  const trimmedLine = line.trim();
  if (!trimmedLine || trimmedLine.startsWith(':') || trimmedLine === 'data: [DONE]') return;
  if (!trimmedLine.startsWith('data:')) return;

  const jsonStr = trimmedLine.slice(5).trim();
  try {
    const event = JSON.parse(jsonStr);
    if (event.type === 'text') {
      state.fullContent += event.content || '';
    } else if (event.type === 'done') {
      state.doneData = event;
    } else if (event.type === 'error') {
      throw new Error(event.message || 'Dify 流式响应失败');
    }
  } catch (error) {
    if (error instanceof Error && !jsonStr.startsWith('{')) {
      state.fullContent += jsonStr;
      return;
    }
    throw error;
  }
}

export async function callCozeEdge(options: CozeRequestOptions): Promise<{
  data: CozeResponse | null;
  traceId: string;
  status: number;
  error?: string;
}> {
  const traceId = crypto.randomUUID();
  
  const requestBody = {
    message: options.message,
    conversationId: options.conversationId || '',
    inputs: {
      user_id: options.userId || 'guest',
      trace_id: traceId,
      user_context: options.userContext || '',
      product: options.product,
      catalog: options.catalog || []
    }
  };
  
  try {
    console.log('🚀 [CHAT CLIENT] 开始调用 dify-chat-stream');
    console.log('📤 请求体:', JSON.stringify(requestBody, null, 2));
    
    const { data: { session } } = await supabase.auth.getSession();
    console.log('🔐 用户登录状态:', session ? '已登录' : '未登录');
    
    let lastError: any = null;
    let data: any = null;
    let error: any = null;

    // 重试逻辑
    for (let attempt = 1; attempt <= 2; attempt++) {
      console.log(`🔄 尝试 ${attempt}/2...`);
      
      try {
        const invokePromise = fetch(`${SUPABASE_URL}/functions/v1/dify-chat-stream`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${session?.access_token || SUPABASE_ANON_KEY}`,
            'X-Trace-Id': traceId,
            'X-User-Id': options.userId || 'guest'
          },
          body: JSON.stringify(requestBody)
        });
        
        const timeoutPromise = new Promise<never>((_, reject) => {
          setTimeout(() => reject(new Error('AI响应超时，请重新发送消息')), 65000);
        });
        
        const response = await Promise.race([invokePromise, timeoutPromise]);
        if (!response.ok) {
          throw new Error(`Dify 请求失败 (${response.status}): ${await response.text()}`);
        }
        if (!response.body) {
          throw new Error('响应体为空');
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        const state = { fullContent: '', doneData: null as StreamDonePayload | null };
        let buffer = '';

        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            if (buffer.trim()) processDifyStreamLine(buffer, state);
            break;
          }

          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop() || '';
          for (const line of lines) processDifyStreamLine(line, state);
        }

        data = {
          ...(state.doneData || {}),
          title: state.doneData?.title || options.message,
          answer: state.fullContent,
        };
        error = null;
        lastError = null;

        if (data) {
          break;
        }
        
        lastError = error;
        
        if (attempt === 1) {
          console.log('⏳ Edge Function 可能正在启动，2秒后重试...');
          await new Promise(resolve => setTimeout(resolve, 2000));
        }
      } catch (e) {
        lastError = e;
        console.error(`❌ 尝试 ${attempt} 失败:`, e);
        
        if (attempt === 1) {
          await new Promise(resolve => setTimeout(resolve, 2000));
        }
      }
    }
    
    error = error || lastError;
    
    if (error) {
      console.error('❌ Dify Chat Functions 错误:', error);
      
      const errorMessage = error.message || String(error);
      let friendlyMessage = '抱歉，系统暂时繁忙';
      
      if (errorMessage.includes('Failed to fetch') || errorMessage.includes('NetworkError')) {
        friendlyMessage = '网络连接不稳定，请重新发送消息试试';
      } else if (errorMessage.includes('timeout') || errorMessage.includes('超时')) {
        friendlyMessage = 'AI响应超时（65秒），请重新发送消息';
      }
      
      return {
        data: null,
        traceId,
        status: 0,
        error: friendlyMessage
      };
    }
    
    if (!data) {
      return {
        data: null,
        traceId,
        status: 0,
        error: '响应数据为空'
      };
    }
    
    console.log('✅ 成功获取 Dify 响应');
    
    const rawData = data as any;
    
    if (rawData.error) {
      return {
        data: null,
        traceId: rawData.meta?.probe_id || traceId,
        status: 200,
        error: `系统繁忙，请稍后再试（追踪码：${rawData.meta?.probe_id || traceId}）`
      };
    }
    
    const cozeResponse: CozeResponse = {
      title: rawData.title || options.message,
      intent: rawData.intent || "GENERAL",
      sentiment: rawData.sentiment || "NEUTRAL",
      highlights: rawData.highlights || [],
      picks: rawData.picks || [],
      comparison: rawData.comparison,
      next: rawData.next || [],
      meta: {
        platform: rawData.meta?.platform || 'dify-stream',
        user: rawData.meta?.user || options.userId,
        catalog_count: rawData.meta?.catalog_count ?? 0,
        probe_id: rawData.meta?.probe_id || traceId
      },
      conversation_id: rawData.conversation_id,
      answer: rawData.answer
    };
    
    console.log('📊 Dify 响应:', {
      platform: cozeResponse.meta.platform,
      picks: cozeResponse.picks.length,
      conversation_id: cozeResponse.conversation_id || '(new)'
    });
    
    return { 
      data: cozeResponse, 
      traceId: cozeResponse.meta.probe_id, 
      status: 200
    };
    
  } catch (error) {
    console.error('❌ 调用 Coze Edge Function 失败:', error);
    
    return {
      data: null,
      traceId,
      status: 0,
      error: '网络连接不稳定，请重新发送消息试试'
    };
  }
}
