import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { isA2aRequestAuthorized } from "@/lib/a2a-auth";

type PublicMcpTool = {
  name: string;
  description?: string;
  inputSchema?: unknown;
};

/**
 * A2A MCP Discovery Endpoint
 * 
 * Allows Agents to discover what MCP tools another Agent exposes.
 * e.g., A frontend agent might discover that a backend agent exposes a `generate_db_schema` tool,
 * and the frontend agent can call it and pay a micro-transaction fee.
 */
export async function GET(request: Request) {
  if (!isA2aRequestAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const { searchParams } = new URL(request.url);
    const agentId = searchParams.get("agent_id");

    if (!agentId) {
      return NextResponse.json({ error: "Missing agent_id parameter" }, { status: 400 });
    }

    const agent = await prisma.agentProfile.findUnique({
      where: { agent_id: agentId }
    });

    if (!agent) {
      return NextResponse.json({ error: "Agent not found" }, { status: 404 });
    }

    // Default MCP tools if none explicitly defined in capabilities
    const defaultMcp = {
      tools: [
        {
          name: "request_quote",
          description: "Request a quote for a specific coding task",
          inputSchema: {
            type: "object",
            properties: {
              task_description: { type: "string" },
              urgency: { type: "string", enum: ["LOW", "HIGH"] }
            },
            required: ["task_description"]
          }
        }
      ]
    };

    const capabilities = agent.capabilities;
    const configuredTools = typeof capabilities === "object" && capabilities !== null && !Array.isArray(capabilities)
      ? (capabilities as { mcp_tools?: unknown }).mcp_tools
      : undefined;
    const mcpTools: PublicMcpTool[] = Array.isArray(configuredTools)
      ? configuredTools
          .filter((tool): tool is PublicMcpTool => {
            return typeof tool === "object" && tool !== null &&
              typeof (tool as { name?: unknown }).name === "string";
          })
          .map((tool) => ({
            name: tool.name,
            description: tool.description,
            inputSchema: tool.inputSchema,
          }))
      : defaultMcp.tools;

    return NextResponse.json({
      agent_id: agent.agent_id,
      mcp_servers: {
        agent_server: {
          description: `Direct MCP interface for Agent ${agent.agent_id}`,
          tools: mcpTools
        }
      }
    });

  } catch (error: unknown) {
    console.error("[MCP Discover Error]", error);
    return NextResponse.json({ error: "Failed to fetch MCP capabilities" }, { status: 500 });
  }
}
