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

/**
 * Coze Langchain API 客户端
 * 
 * 用于调用部署在 Coze 上的 Langchain 服务
 * API 端点: https://dbwbtkkt9g.coze.site/stream_run
 */

/**
 * 从 Coze 响应中提取文本内容
 * Coze 的 SSE 格式:
 * event: message
 * data: {"type": "answer", "content": {"answer": "实际回答内容"}}
 * 或
 * data: {"type": "message_end", "content": {"message_end": {"code": "0", "message": "success"}}}
 */
function extractTextContent(obj: unknown): string {
  if (typeof obj === 'string') {
    return obj;
  }
  
  if (obj === null || obj === undefined) {
    return '';
  }
  
  if (typeof obj !== 'object') {
    return String(obj);
  }
  
  const data = obj as Record<string, unknown>;
  
  // Coze 格式: content.answer
  if (data.content && typeof data.content === 'object') {
    const content = data.content as Record<string, unknown>;
    
    // 检查 answer 字段 (主要回答内容)
    if (typeof content.answer === 'string' && content.answer) {
      return content.answer;
    }
    
    // 检查 thinking 字段 (思考过程)
    if (typeof content.thinking === 'string' && content.thinking) {
      return content.thinking;
    }
    
    // 检查错误信息
    if (content.message_end && typeof content.message_end === 'object') {
      const msgEnd = content.message_end as Record<string, unknown>;
      if (msgEnd.code !== '0' && msgEnd.code !== 0 && typeof msgEnd.message === 'string') {
        // 返回错误信息
        return `[Coze Error: ${msgEnd.message}]`;
      }
    }
    
    // 检查 error 字段
    if (content.error && typeof content.error === 'object') {
      const error = content.error as Record<string, unknown>;
      if (typeof error.message === 'string') {
        return `[Error: ${error.message}]`;
      }
    }
  }
  
  // OpenAI 格式: choices[0].delta.content
  if (Array.isArray(data.choices) && data.choices[0]) {
    const choice = data.choices[0] as Record<string, unknown>;
    if (choice.delta && typeof choice.delta === 'object') {
      const delta = choice.delta as Record<string, unknown>;
      if (typeof delta.content === 'string') {
        return delta.content;
      }
    }
    if (choice.message && typeof choice.message === 'object') {
      const message = choice.message as Record<string, unknown>;
      if (typeof message.content === 'string') {
        return message.content;
      }
    }
  }
  
  // 常见字段
  const fields = ['answer', 'content', 'text', 'message', 'output', 'response', 'result'];
  for (const field of fields) {
    if (field in data) {
      const value = data[field];
      if (typeof value === 'string' && value) {
        return value;
      }
    }
  }
  
  return '';
}

export interface CozeLangchainRequest {
  /** 输入文本 */
  text: string;
  /** 是否使用流式响应 */
  stream?: boolean;
  /** 会话ID (用于上下文保持) */
  conversation_id?: string;
  /** 额外参数 */
  extra_params?: Record<string, unknown>;
}

export interface CozeLangchainResponse {
  success: boolean;
  data?: unknown;
  error?: string;
  trace_id?: string;
}

/**
 * 调用 Coze Langchain API (非流式)
 */
export async function callCozeLangchain(
  request: CozeLangchainRequest
): Promise<CozeLangchainResponse> {
  try {
    const { data, error } = await supabase.functions.invoke("coze-langchain", {
      body: {
        ...request,
        stream: false,
      },
    });

    if (error) {
      console.error("[CozeLangchain] Invoke error:", error);
      return {
        success: false,
        error: error.message || "调用失败",
      };
    }

    return data as CozeLangchainResponse;
  } catch (err) {
    console.error("[CozeLangchain] Error:", err);
    return {
      success: false,
      error: err instanceof Error ? err.message : "未知错误",
    };
  }
}

/**
 * 调用 Coze Langchain API (流式)
 * 
 * @param request 请求参数
 * @param onChunk 接收到数据块时的回调
 * @param onDone 完成时的回调
 * @param onError 错误时的回调
 */
export async function streamCozeLangchain(
  request: CozeLangchainRequest,
  onChunk: (chunk: string) => void,
  onDone: () => void,
  onError?: (error: Error) => void
): Promise<void> {
  
  const SUPABASE_URL = import.meta.env.VITE_SUPABASE_URL;
  const SUPABASE_ANON_KEY = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;

  try {
    const response = await fetch(`${SUPABASE_URL}/functions/v1/coze-langchain`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${SUPABASE_ANON_KEY}`,
      },
      body: JSON.stringify({
        ...request,
        stream: true,
      }),
    });

    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()) {
          onChunk(buffer);
        }
        break;
      }

      buffer += decoder.decode(value, { stream: true });
      
      // 解析 SSE 格式 - Coze 返回格式可能是:
      // event: message
      // data: {"content": "..."}
      // 或者直接是 JSON 数据
      const lines = buffer.split("\n");
      buffer = lines.pop() || ""; // 保留最后一个不完整的行
      
      for (const line of lines) {
        const trimmedLine = line.trim();
        
        // 跳过空行和事件行
        if (!trimmedLine || trimmedLine.startsWith("event:") || trimmedLine.startsWith(":")) {
          continue;
        }
        
        // 处理 data: 前缀的行
        let dataContent = trimmedLine;
        if (trimmedLine.startsWith("data:")) {
          dataContent = trimmedLine.slice(5).trim();
        }
        
        if (!dataContent || dataContent === "[DONE]") {
          continue;
        }
        
        try {
          const parsed = JSON.parse(dataContent);
          // 提取实际文本内容 - 处理各种可能的格式
          const text = extractTextContent(parsed);
          if (text) {
            onChunk(text);
          }
        } catch {
          // 非 JSON 格式，直接使用（如果是纯文本）
          if (dataContent && typeof dataContent === 'string' && !dataContent.startsWith('{')) {
            onChunk(dataContent);
          }
        }
      }
    }

    onDone();
  } catch (err) {
    console.error("[CozeLangchain Stream] Error:", err);
    if (onError) {
      onError(err instanceof Error ? err : new Error("未知错误"));
    }
  }
}

/**
 * 测试 Coze Langchain 连接
 */
export async function testCozeLangchainConnection(): Promise<{
  success: boolean;
  message: string;
  latencyMs: number;
}> {
  const startTime = Date.now();
  
  try {
    const result = await callCozeLangchain({
      text: "ping",
    });

    const latencyMs = Date.now() - startTime;

    if (result.success) {
      return {
        success: true,
        message: "连接成功",
        latencyMs,
      };
    } else {
      return {
        success: false,
        message: result.error || "连接失败",
        latencyMs,
      };
    }
  } catch (err) {
    return {
      success: false,
      message: err instanceof Error ? err.message : "连接测试失败",
      latencyMs: Date.now() - startTime,
    };
  }
}

/**
 * 生成外部调用示例代码
 */
export function generateCozeLangchainExample(): string {
  return `
# Coze Langchain API 调用示例

## 端点信息
- URL: https://dbwbtkkt9g.coze.site/stream_run
- Method: POST
- Content-Type: application/json

## 通过 Edge Function 调用 (推荐)

### cURL 示例
\`\`\`bash
curl -X POST "https://tlsofopqzrzuduinsicm.supabase.co/functions/v1/coze-langchain" \\
  -H "Content-Type: application/json" \\
  -H "Authorization: Bearer YOUR_SUPABASE_ANON_KEY" \\
  -d '{
    "text": "你好，请介绍一下你自己",
    "stream": false
  }'
\`\`\`

### JavaScript 示例
\`\`\`javascript
import { callCozeLangchain, streamCozeLangchain } from "@/utils/cozeLangchainClient";

// 非流式调用
const result = await callCozeLangchain({
  text: "分析一下今天的销售数据",
});

console.log(result.data);

// 流式调用
await streamCozeLangchain(
  { text: "生成一份营销报告" },
  (chunk) => console.log("收到:", chunk),
  () => console.log("完成"),
  (error) => console.error("错误:", error)
);
\`\`\`

### Python 示例
\`\`\`python
import requests

response = requests.post(
    "https://tlsofopqzrzuduinsicm.supabase.co/functions/v1/coze-langchain",
    headers={
        "Content-Type": "application/json",
        "Authorization": "Bearer YOUR_SUPABASE_ANON_KEY"
    },
    json={
        "text": "你好，请介绍一下你自己",
        "stream": False
    }
)

print(response.json())
\`\`\`
`.trim();
}
