import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { RegisterAgentCardRequestSchema } from "@agent-bounty/contracts";

const PUBLIC_MCP_BETA_TOKEN = (process.env.PUBLIC_MCP_BETA_TOKEN || "").trim();

function isAuthorizedMcpRequest(request: NextRequest) {
  const authHeader = request.headers.get("Authorization");
  if (!authHeader?.startsWith("Bearer ")) {
    return false;
  }

  const token = authHeader.slice("Bearer ".length);
  return Boolean(process.env.API_KEY && token === process.env.API_KEY) ||
    Boolean(PUBLIC_MCP_BETA_TOKEN && token === PUBLIC_MCP_BETA_TOKEN);
}

export async function POST(req: NextRequest) {
  if (!isAuthorizedMcpRequest(req)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const json = await req.json();
    
    // Validate request using 2026 Agent Card standard
    const parsed = RegisterAgentCardRequestSchema.safeParse(json);
    if (!parsed.success) {
      return NextResponse.json({ error: "Invalid Agent Card schema", details: parsed.error }, { status: 400 });
    }
    
    const card = parsed.data.card;

    // Phase 3.1: Semantic Capability Parsing
    // In production, this would call an LLM (e.g. OpenAI/Gemini) to extract structured tags.
    // Here we use a heuristic-based MVP parser to extract technical stacks from the description.
    const description = card.description?.toLowerCase() || "";
    const semanticTags: string[] = [];
    if (description.includes("react") || description.includes("nextjs")) semanticTags.push("React");
    if (description.includes("python") || description.includes("django")) semanticTags.push("Python");
    if (description.includes("contract") || description.includes("solidity")) semanticTags.push("SmartContracts");
    if (description.includes("sql") || description.includes("prisma")) semanticTags.push("Database");

    const enrichedCapabilities = {
      ...JSON.parse(JSON.stringify(card)),
      semantic_tags: semanticTags,
    };

    const existingAgent = await prisma.agentProfile.findUnique({
      where: { agent_id: card.agent_id },
    });

    if (
      existingAgent?.wallet_address &&
      card.x402_wallet_address &&
      existingAgent.wallet_address !== card.x402_wallet_address
    ) {
      return NextResponse.json({ error: "Registered wallet cannot be overwritten" }, { status: 409 });
    }

    if (existingAgent) {
      await prisma.agentProfile.update({
        where: { agent_id: card.agent_id },
        data: {
          capabilities: enrichedCapabilities,
          wallet_address: existingAgent.wallet_address || card.x402_wallet_address,
        },
      });
    } else {
      await prisma.agentProfile.create({
        data: {
        agent_id: card.agent_id,
        type: "BUILDER",
        status: "PENDING",
        capabilities: enrichedCapabilities,
        wallet_address: card.x402_wallet_address,
      }
      });
    }

    return NextResponse.json(
      { status: "SUCCESS", message: `Agent Card registered for ${card.name}` } as const,
      { status: 200 }
    );

  } catch (err: unknown) {
    console.error("[AgentCard] Registration Error:", err);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
