import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { AGENT_DEFINITIONS, getAgentDefinition } from '@/lib/agent-hierarchy/agents';
import { MODULE_REGISTRY, getModule } from '@/lib/modules/registry';

export const dynamic = 'force-dynamic';

/**
 * GET /api/agents/profiles
 * Returns all agent profiles with their module assignments, capabilities, and status.
 */
export async function GET() {
  try {
    // Fetch live agent data from DB
    const dbAgents = await prisma.domainAgent.findMany({
      include: {
        _count: {
          select: {
            memories: true,
            sentMessages: true,
            receivedMessages: true,
          },
        },
      },
    });

    // Fetch module configs
    const moduleConfigs = await prisma.moduleConfig.findMany();
    const enabledModules = new Set(moduleConfigs.filter((m: { isEnabled: boolean; moduleId: string }) => m.isEnabled).map((m: { moduleId: string }) => m.moduleId));

    // Merge definitions with DB state
    const profiles = AGENT_DEFINITIONS.map(def => {
      const dbAgent = dbAgents.find((a: any) => a.agentId === def.agentId);
      const mod = def.moduleId ? getModule(def.moduleId) : null;
      const moduleEnabled = def.moduleId ? enabledModules.has(def.moduleId) : true;

      return {
        agentId: def.agentId,
        name: def.name,
        title: def.title,
        domain: def.domain,
        parentAgentId: def.parentAgentId,
        moduleId: def.moduleId,
        moduleName: mod?.name || (def.parentAgentId === null ? 'All Modules (CEO)' : 'Unassigned'),
        moduleEnabled,
        avatarColor: def.avatarColor,
        personality: def.personality,
        capabilities: def.capabilities,
        escalationTriggers: def.escalationTriggers,
        status: dbAgent?.status || (moduleEnabled ? 'active' : 'dormant'),
        maturityLevel: dbAgent?.maturityLevel ?? 0,
        xp: dbAgent?.xp ?? 0,
        totalInteractions: dbAgent?.totalInteractions ?? 0,
        lastActiveAt: dbAgent?.lastActiveAt?.toISOString() || null,
        memoryCount: dbAgent?._count?.memories ?? 0,
        messagesSent: dbAgent?._count?.sentMessages ?? 0,
        messagesReceived: dbAgent?._count?.receivedMessages ?? 0,
        // Module-agent mapping for hierarchy view
        associatedModules: MODULE_REGISTRY
          .filter(m => m.agentId === def.agentId)
          .map(m => ({ moduleId: m.moduleId, name: m.name, enabled: enabledModules.has(m.moduleId) })),
      };
    });

    return NextResponse.json({
      profiles,
      summary: {
        totalAgents: profiles.length,
        activeAgents: profiles.filter(p => p.status === 'active').length,
        dormantAgents: profiles.filter(p => p.status === 'dormant').length,
        totalXP: profiles.reduce((sum, p) => sum + p.xp, 0),
        totalMemories: profiles.reduce((sum, p) => sum + p.memoryCount, 0),
      },
    });
  } catch (error) {
    console.error('Failed to fetch agent profiles:', error);
    return NextResponse.json({ error: 'Failed to fetch agent profiles' }, { status: 500 });
  }
}
