import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import axios from 'axios';
import { cronUnauthorizedResponse, isCronRequestAuthorized } from '@/lib/cron-auth';

export const dynamic = 'force-dynamic';

const DEFAULT_AGENT_REGISTRIES = [
  'https://tsenyang.com/.well-known/agent-card.json',
];

function getAgentRegistries() {
  const configured = (process.env.A2A_DISCOVERY_AGENT_CARD_URLS || "")
    .split(",")
    .map((url) => url.trim())
    .filter(Boolean);

  return configured.length > 0 ? configured : DEFAULT_AGENT_REGISTRIES;
}

function isSafeDiscoveryUrl(value: string) {
  try {
    const url = new URL(value);
    return url.protocol === "https:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname);
  } catch {
    return false;
  }
}

export async function GET(request: Request) {
  if (!isCronRequestAuthorized(request)) {
    return cronUnauthorizedResponse("A2A Discovery");
  }
  return handleDiscovery();
}

export async function POST(request: Request) {
  if (!isCronRequestAuthorized(request)) {
    return cronUnauthorizedResponse("A2A Discovery");
  }
  return handleDiscovery();
}

async function handleDiscovery() {
  console.log('[A2A Discovery] Starting agent discovery scan...');
  let newAgentsCount = 0;
  let updatedAgentsCount = 0;

  for (const url of getAgentRegistries()) {
    if (!isSafeDiscoveryUrl(url)) {
      console.warn(`[A2A Discovery] Skipping unsafe agent card URL: ${url}`);
      continue;
    }

    try {
      console.log(`[A2A Discovery] Scanning ${url}`);
      const res = await axios.get(url, { timeout: 5000, maxRedirects: 0 });
      const card = res.data;

      // Basic validation for Agent Card
      if (!card || !card.agentId || !card.type) {
        console.warn(`[A2A Discovery] Invalid agent card at ${url}`);
        continue;
      }

      // Check if it's a BUILDER or capable of solving tasks
      if (card.type !== 'BUILDER' && !card.capabilities?.includes('submit_work')) {
        console.log(`[A2A Discovery] Agent ${card.agentId} is not a BUILDER. Skipping.`);
        continue;
      }

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

      if (existingAgent) {
        // Update contact endpoints and capabilities
        await prisma.agentProfile.update({
          where: { id: existingAgent.id },
          data: {
            capabilities: card.capabilities || null,
            contact_endpoints: card.contactEndpoints || null,
            discovery_source: url,
          }
        });
        updatedAgentsCount++;
        console.log(`[A2A Discovery] Updated existing agent ${card.agentId}`);
      } else {
        // Create new agent profile
        await prisma.agentProfile.create({
          data: {
            agent_id: card.agentId,
            type: 'BUILDER',
            status: 'PENDING',
            capabilities: card.capabilities || null,
            contact_endpoints: card.contactEndpoints || null,
            discovery_source: url,
          }
        });
        newAgentsCount++;
        console.log(`[A2A Discovery] Discovered pending agent ${card.agentId}`);
      }

    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : String(error);
      console.error(`[A2A Discovery] Failed to scan ${url}: ${message}`);
    }
  }

  return NextResponse.json({
    message: 'Discovery scan completed',
    new_agents: newAgentsCount,
    updated_agents: updatedAgentsCount
  });
}
