import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { getAgentHierarchyStatus, initializeAgentHierarchy } from '@/lib/agent-hierarchy/engine';

export const dynamic = 'force-dynamic';

/**
 * GET /api/agents/hierarchy
 * Returns the full agent hierarchy with status and stats.
 * Initializes agents on first call.
 */
export async function GET() {
  try {
    let agentCount = await prisma.domainAgent.count();
    if (agentCount === 0) {
      await initializeAgentHierarchy();
    }

    const status = await getAgentHierarchyStatus();
    return NextResponse.json(status);
  } catch (error) {
    console.error('Failed to get agent hierarchy:', error);
    return NextResponse.json({ error: 'Failed to fetch agent hierarchy' }, { status: 500 });
  }
}

/**
 * POST /api/agents/hierarchy
 * Force re-initialize the agent hierarchy.
 */
export async function POST() {
  try {
    await initializeAgentHierarchy();
    const status = await getAgentHierarchyStatus();
    return NextResponse.json({ success: true, ...status });
  } catch (error) {
    console.error('Failed to initialize agents:', error);
    return NextResponse.json({ error: 'Failed to initialize agents' }, { status: 500 });
  }
}
