/**
 * Agent Debug Client - Langchain/Coze 与 Lovable 联调辅助工具
 * 
 * 用途:
 * 1. 方便外部 Agent (Langchain/Coze) 调用 Lovable 系统
 * 2. 提供标准化的请求/响应格式
 * 3. 支持调试模式，返回详细执行轨迹
 */

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

// Agent 来源类型
export type AgentSource = "coze" | "langchain" | "dify" | "custom" | "lovable";

// 目标 Agent 类型
export type TargetAgent = "marketing" | "product" | "finance" | "service" | "manager";

// 调试请求参数
export interface AgentDebugRequest {
  /** 用户消息 (必填) */
  message: string;
  /** 来源 Agent 标识 */
  agentSource?: AgentSource;
  /** 目标 Agent 类型 */
  targetAgent?: TargetAgent;
  /** 会话 ID (多轮对话) */
  conversationId?: string;
  /** 用户上下文 */
  userContext?: Record<string, unknown>;
  /** 是否开启调试模式 */
  debugMode?: boolean;
  /** 外部 trace_id */
  externalTraceId?: string;
}

// 调试轨迹
export interface DebugTrace {
  timestamp: string;
  step: string;
  duration_ms: number;
  data?: unknown;
}

// 调试响应
export interface AgentDebugResponse {
  success: boolean;
  traceId: string;
  externalTraceId?: string;
  agentSource: string;
  targetAgent: string;
  response: {
    text?: string;
    uiSchema?: unknown;
    actions?: unknown[];
    suggestions?: string[];
  };
  debug?: {
    requestReceived: string;
    totalDurationMs: number;
    traces: DebugTrace[];
    systemState?: Record<string, unknown>;
  };
  error?: string;
}

// 转换响应格式 (snake_case -> camelCase)
function transformResponse(data: Record<string, unknown>): AgentDebugResponse {
  return {
    success: data.success as boolean,
    traceId: data.trace_id as string,
    externalTraceId: data.external_trace_id as string | undefined,
    agentSource: data.agent_source as string,
    targetAgent: data.target_agent as string,
    response: {
      text: (data.response as Record<string, unknown>)?.text as string | undefined,
      uiSchema: (data.response as Record<string, unknown>)?.ui_schema,
      actions: (data.response as Record<string, unknown>)?.actions as unknown[] | undefined,
      suggestions: (data.response as Record<string, unknown>)?.suggestions as string[] | undefined,
    },
    debug: data.debug ? {
      requestReceived: (data.debug as Record<string, unknown>).request_received as string,
      totalDurationMs: (data.debug as Record<string, unknown>).total_duration_ms as number,
      traces: (data.debug as Record<string, unknown>).traces as DebugTrace[],
      systemState: (data.debug as Record<string, unknown>).system_state as Record<string, unknown> | undefined,
    } : undefined,
    error: data.error as string | undefined,
  };
}

/**
 * 调用 Agent Debug API
 * 
 * @example
 * // 基本调用
 * const result = await callAgentDebug({
 *   message: "查看本月销售报表",
 *   targetAgent: "marketing",
 * });
 * 
 * @example
 * // 调试模式
 * const result = await callAgentDebug({
 *   message: "分析库存预警",
 *   targetAgent: "product",
 *   agentSource: "coze",
 *   debugMode: true,
 *   externalTraceId: "coze-trace-12345",
 * });
 */
export async function callAgentDebug(request: AgentDebugRequest): Promise<AgentDebugResponse> {
  const {
    message,
    agentSource = "lovable",
    targetAgent = "marketing",
    conversationId,
    userContext,
    debugMode = false,
    externalTraceId,
  } = request;

  console.log(`[AgentDebug] Calling: ${agentSource} -> ${targetAgent}`);
  console.log(`[AgentDebug] Message: ${message.substring(0, 100)}...`);

  const { data, error } = await supabase.functions.invoke("agent-debug", {
    body: {
      message,
      agent_source: agentSource,
      target_agent: targetAgent,
      conversation_id: conversationId,
      user_context: userContext,
      debug_mode: debugMode,
      external_trace_id: externalTraceId,
    },
  });

  if (error) {
    console.error("[AgentDebug] Error:", error);
    return {
      success: false,
      traceId: "",
      agentSource,
      targetAgent,
      response: {},
      error: error.message,
    };
  }

  const response = transformResponse(data);
  
  console.log(`[AgentDebug] Response trace_id: ${response.traceId}`);
  if (response.debug) {
    console.log(`[AgentDebug] Duration: ${response.debug.totalDurationMs}ms`);
    console.log(`[AgentDebug] Traces:`, response.debug.traces);
  }

  return response;
}

/**
 * 生成外部 Agent 调用示例代码
 * 用于复制到 Coze/Langchain 中使用
 */
export function generateExternalCallExample(
  supabaseUrl: string,
  targetAgent: TargetAgent = "marketing"
): string {
  return `
// ========================================
// Coze / Langchain 调用 Lovable Agent 示例
// ========================================

// Python (Langchain)
import requests

def call_lovable_agent(message: str, trace_id: str = None):
    url = "${supabaseUrl}/functions/v1/agent-debug"
    headers = {
        "Content-Type": "application/json",
        "x-agent-source": "langchain",
        "x-trace-id": trace_id or ""
    }
    payload = {
        "message": message,
        "target_agent": "${targetAgent}",
        "agent_source": "langchain",
        "debug_mode": True,
        "external_trace_id": trace_id
    }
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

# 使用示例
result = call_lovable_agent("查看本月销售数据", "my-trace-001")
print(result["response"]["text"])


// JavaScript (Coze Plugin)
async function callLovableAgent(message, traceId) {
    const response = await fetch("${supabaseUrl}/functions/v1/agent-debug", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "x-agent-source": "coze",
            "x-trace-id": traceId || ""
        },
        body: JSON.stringify({
            message: message,
            target_agent: "${targetAgent}",
            agent_source: "coze",
            debug_mode: true,
            external_trace_id: traceId
        })
    });
    return await response.json();
}

// 使用示例
const result = await callLovableAgent("分析库存预警", "coze-trace-001");
console.log(result.response.text);
`.trim();
}

/**
 * 快速测试连接
 */
export async function testAgentDebugConnection(): Promise<{
  success: boolean;
  message: string;
  latencyMs: number;
}> {
  const startTime = Date.now();
  
  try {
    const result = await callAgentDebug({
      message: "ping",
      debugMode: true,
      agentSource: "lovable",
    });

    const latencyMs = Date.now() - startTime;

    if (result.success) {
      return {
        success: true,
        message: `连接成功! trace_id: ${result.traceId}`,
        latencyMs,
      };
    } else {
      return {
        success: false,
        message: `连接失败: ${result.error}`,
        latencyMs,
      };
    }
  } catch (e) {
    return {
      success: false,
      message: `连接异常: ${e instanceof Error ? e.message : "Unknown error"}`,
      latencyMs: Date.now() - startTime,
    };
  }
}

// 导出所有类型和函数
export default {
  callAgentDebug,
  generateExternalCallExample,
  testAgentDebugConnection,
};
