import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.39.3";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type, x-trace-id, x-agent-source",
};

/**
 * Agent Debug API - 用于 Langchain/Coze 与 Lovable 联调
 * 
 * 功能:
 * 1. 接收外部 Agent 的请求并记录调试信息
 * 2. 转发到内部 GenUI 系统获取响应
 * 3. 返回标准化的调试响应，包含执行轨迹
 */

interface AgentDebugRequest {
  // 必填: 用户消息
  message: string;
  // 可选: 来源 Agent 标识 (coze, langchain, dify, custom)
  agent_source?: string;
  // 可选: 目标 Agent 类型 (marketing, product, finance, service, manager)
  target_agent?: string;
  // 可选: 会话 ID (用于多轮对话)
  conversation_id?: string;
  // 可选: 用户上下文
  user_context?: Record<string, unknown>;
  // 可选: 是否返回详细调试信息
  debug_mode?: boolean;
  // 可选: 外部 trace_id (用于链路追踪)
  external_trace_id?: string;
}

interface DebugTrace {
  timestamp: string;
  step: string;
  duration_ms: number;
  data?: unknown;
}

interface AgentDebugResponse {
  success: boolean;
  trace_id: string;
  external_trace_id?: string;
  agent_source: string;
  target_agent: string;
  // 响应内容
  response: {
    text?: string;
    ui_schema?: unknown;
    actions?: unknown[];
    suggestions?: string[];
  };
  // 调试信息 (debug_mode=true 时返回)
  debug?: {
    request_received: string;
    total_duration_ms: number;
    traces: DebugTrace[];
    system_state?: Record<string, unknown>;
  };
  // 错误信息
  error?: string;
}

const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!;
const SUPABASE_SERVICE_ROLE_KEY = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;

// Agent 类型到 GenUI 函数的映射
const AGENT_FUNCTION_MAP: Record<string, string> = {
  marketing: "marketing-genui",
  product: "product-genui",
  finance: "finance-genui",
  service: "service-genui",
  manager: "manager-genui",
};

serve(async (req) => {
  const startTime = Date.now();
  const traceId = crypto.randomUUID();
  const traces: DebugTrace[] = [];

  // CORS 预检
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  const addTrace = (step: string, data?: unknown) => {
    traces.push({
      timestamp: new Date().toISOString(),
      step,
      duration_ms: Date.now() - startTime,
      data,
    });
  };

  try {
    addTrace("request_received");

    // 从请求头获取额外信息
    const headerTraceId = req.headers.get("x-trace-id");
    const headerAgentSource = req.headers.get("x-agent-source");

    const body: AgentDebugRequest = await req.json();
    const {
      message,
      agent_source = headerAgentSource || "unknown",
      target_agent = "marketing",
      conversation_id,
      user_context,
      debug_mode = false,
      external_trace_id = headerTraceId,
    } = body;

    addTrace("request_parsed", { 
      message_length: message?.length,
      agent_source,
      target_agent,
      has_conversation_id: !!conversation_id,
    });

    // 参数验证
    if (!message || typeof message !== "string") {
      throw new Error("message 参数是必填的字符串");
    }

    if (!AGENT_FUNCTION_MAP[target_agent]) {
      throw new Error(`不支持的 target_agent: ${target_agent}，可选值: ${Object.keys(AGENT_FUNCTION_MAP).join(", ")}`);
    }

    // 创建 Supabase 客户端
    const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
    addTrace("supabase_client_created");

    // 记录调试日志到数据库 (可选)
    const logEntry = {
      trace_id: traceId,
      external_trace_id,
      agent_source,
      target_agent,
      message,
      user_context,
      created_at: new Date().toISOString(),
    };
    
    // 尝试记录日志，但不阻塞主流程
    (async () => {
      try {
        await supabase.from("agent_debug_logs").insert(logEntry);
        console.log(`[Debug] Log saved: ${traceId}`);
      } catch (e) {
        const msg = e instanceof Error ? e.message : String(e);
        console.log(`[Debug] Log save skipped (table may not exist): ${msg}`);
      }
    })();

    addTrace("log_entry_queued");

    // 调用对应的 GenUI 函数
    const targetFunction = AGENT_FUNCTION_MAP[target_agent];
    addTrace("calling_genui", { function: targetFunction });

    const genUIResponse = await fetch(`${SUPABASE_URL}/functions/v1/${targetFunction}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${SUPABASE_SERVICE_ROLE_KEY}`,
        "x-trace-id": traceId,
      },
      body: JSON.stringify({
        message,
        conversation_id,
        user_context: {
          ...user_context,
          agent_source,
          external_trace_id,
        },
      }),
    });

    addTrace("genui_response_received", { 
      status: genUIResponse.status,
      ok: genUIResponse.ok,
    });

    if (!genUIResponse.ok) {
      const errorText = await genUIResponse.text();
      throw new Error(`GenUI 调用失败 (${genUIResponse.status}): ${errorText}`);
    }

    const genUIData = await genUIResponse.json();
    addTrace("genui_data_parsed", { 
      has_text: !!genUIData.text || !!genUIData.answer,
      has_ui_schema: !!genUIData.ui_schema,
      has_actions: !!genUIData.actions,
    });

    // 构建响应
    const response: AgentDebugResponse = {
      success: true,
      trace_id: traceId,
      external_trace_id: external_trace_id ?? undefined,
      agent_source,
      target_agent,
      response: {
        text: genUIData.text || genUIData.answer || genUIData.message,
        ui_schema: genUIData.ui_schema,
        actions: genUIData.actions,
        suggestions: genUIData.suggestions || genUIData.quick_actions,
      },
    };

    // 调试模式下返回详细信息
    if (debug_mode) {
      addTrace("debug_info_compiled");
      response.debug = {
        request_received: new Date(startTime).toISOString(),
        total_duration_ms: Date.now() - startTime,
        traces,
        system_state: {
          target_function: targetFunction,
          supabase_url: SUPABASE_URL,
        },
      };
    }

    console.log(`[AgentDebug] ${traceId} | ${agent_source} -> ${target_agent} | ${Date.now() - startTime}ms`);

    return new Response(JSON.stringify(response), {
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });

  } catch (error) {
    const errMsg = (error instanceof Error ? error.message : String(error));
    console.error(`[AgentDebug] Error:`, error);
    addTrace("error", { message: errMsg });

    const errorResponse: AgentDebugResponse = {
      success: false,
      trace_id: traceId,
      agent_source: "unknown",
      target_agent: "unknown",
      response: {},
      error: (error instanceof Error ? error.message : "Unknown error"),
      debug: {
        request_received: new Date(startTime).toISOString(),
        total_duration_ms: Date.now() - startTime,
        traces,
      },
    };

    return new Response(JSON.stringify(errorResponse), {
      status: 400,
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  }
});
