/**
 * Coze 流式响应客户端
 * 支持 SSE 流式输出，实时显示 AI 回复
 */

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

interface CozeStreamOptions {
  message: string;
  userId: string;
  conversationId?: string;
  userContext?: string;
  catalog?: Array<{
    id: string;
    name: string;
    price: number;
    stock_quantity?: number;
    category?: string;
    description?: string;
  }>;
}

interface StreamTextEvent {
  type: 'text';
  content: string;
}

interface StreamDoneEvent {
  type: 'done';
  intent: 'SHOPPING' | 'AFTERSALES' | 'GENERAL' | 'COMPARE';
  picks: Array<{ product_id: string; note: string }>;
  highlights: string[];
  meta: {
    platform: string;
    user: string;
    catalog_count: number;
    probe_id: string;
  };
  conversation_id?: string;
}

interface StreamErrorEvent {
  type: 'error';
  message: string;
}

type StreamEvent = StreamTextEvent | StreamDoneEvent | StreamErrorEvent;

export interface CozeStreamCallbacks {
  onText: (text: string) => void;
  onDone: (data: StreamDoneEvent) => void;
  onError: (error: string) => void;
}

/**
 * 调用 Coze 流式 API
 */
export async function streamCozeChat(
  options: CozeStreamOptions,
  callbacks: CozeStreamCallbacks
): Promise<void> {
  const traceId = crypto.randomUUID();
  
  // 获取 Supabase session
  const { data: { session } } = await supabase.auth.getSession();
  
  const SUPABASE_URL = import.meta.env.VITE_SUPABASE_URL;
  const SUPABASE_ANON_KEY = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;

  const requestBody = {
    message: options.message,
    conversationId: options.conversationId || '',
    inputs: {
      user_id: options.userId || 'guest',
      trace_id: traceId,
      user_context: options.userContext || '',
      catalog: options.catalog || []
    }
  };

  try {
    console.log('🚀 [COZE STREAM] 开始流式调用');
    
    const response = await fetch(`${SUPABASE_URL}/functions/v1/coze-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)
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`请求失败 (${response.status}): ${errorText}`);
    }

    if (!response.body) {
      throw new Error('响应体为空');
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        // 处理剩余 buffer
        if (buffer.trim()) {
          processSSELine(buffer, callbacks);
        }
        break;
      }

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

    console.log('✅ [COZE STREAM] 流式调用完成');

  } catch (error) {
    console.error('❌ [COZE STREAM] 错误:', error);
    callbacks.onError(error instanceof Error ? error.message : '流式请求失败');
  }
}

function processSSELine(line: string, callbacks: CozeStreamCallbacks) {
  const trimmedLine = line.trim();
  
  if (!trimmedLine || trimmedLine.startsWith(':')) return;
  
  if (trimmedLine === 'data: [DONE]') return;
  
  if (trimmedLine.startsWith('data:')) {
    const jsonStr = trimmedLine.slice(5).trim();
    
    try {
      const event: StreamEvent = JSON.parse(jsonStr);
      
      switch (event.type) {
        case 'text':
          callbacks.onText(event.content);
          break;
        case 'done':
          callbacks.onDone(event);
          break;
        case 'error':
          callbacks.onError(event.message);
          break;
      }
    } catch (e) {
      // 非 JSON，可能是纯文本
      if (jsonStr && !jsonStr.startsWith('{')) {
        callbacks.onText(jsonStr);
      }
    }
  }
}

/**
 * 测试流式连接
 */
export async function testCozeStreamConnection(): Promise<{
  success: boolean;
  message: string;
  latencyMs: number;
}> {
  const startTime = Date.now();
  let success = false;
  let message = '';
  
  try {
    await streamCozeChat(
      {
        message: 'ping',
        userId: 'test',
        catalog: []
      },
      {
        onText: () => { success = true; },
        onDone: () => { success = true; message = '连接成功'; },
        onError: (err) => { message = err; }
      }
    );
  } catch (err) {
    message = err instanceof Error ? err.message : '连接失败';
  }

  return {
    success,
    message: message || (success ? '连接成功' : '连接失败'),
    latencyMs: Date.now() - startTime
  };
}
