/**
 * Agent Memory API
 * 
 * CRUD operations for agent memories and cross-agent knowledge sharing.
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

// GET - Query memories
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const agentId = searchParams.get('agentId');
    const category = searchParams.get('category');
    const scope = searchParams.get('scope') || 'agent'; // 'agent' | 'shared' | 'all'
    const limit = parseInt(searchParams.get('limit') || '50');
    const minImportance = parseFloat(searchParams.get('minImportance') || '0');

    let memories: any[] = [];

    if (scope === 'agent' || scope === 'all') {
      if (!agentId) {
        return NextResponse.json({ error: 'agentId required for agent memories' }, { status: 400 });
      }

      const agentMemories = await prisma.domainAgentMemory.findMany({
        where: {
          agentId,
          ...(category && { category }),
          importance: { gte: minImportance }
        },
        orderBy: { importance: 'desc' },
        take: limit
      });

      memories = agentMemories.map((m: any) => ({ ...m, scope: 'agent' }));
    }

    if (scope === 'shared' || scope === 'all') {
      const sharedMemories = await prisma.ghostMemory.findMany({
        where: {
          ...(category && { category })
        },
        orderBy: { confidence: 'desc' },
        take: limit
      });

      memories = [...memories, ...sharedMemories.map((m: any) => ({ ...m, scope: 'shared' }))];
    }

    return NextResponse.json({
      success: true,
      memories,
      count: memories.length
    });
  } catch (error: any) {
    console.error('Error querying memories:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

// POST - Create memory
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      agentId,
      category,
      key,
      content,
      confidence = 0.8,
      importance = 0.5,
      source,
      scope = 'agent',
      expiresAt
    } = body;

    if (!category || !key) {
      return NextResponse.json({ error: 'category and key are required' }, { status: 400 });
    }

    let memory;

    if (scope === 'shared') {
      // Shared knowledge (Ghost Memory)
      memory = await prisma.ghostMemory.upsert({
        where: {
          category_key: { category, key }
        },
        update: {
          value: content,
          confidence,
          source: agentId ? `agent:${agentId}` : source,
          usageCount: { increment: 1 },
          lastUsed: new Date(),
          updatedAt: new Date()
        },
        create: {
          id: `ghost_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          category,
          key,
          value: content,
          confidence,
          source: agentId ? `agent:${agentId}` : source,
          updatedAt: new Date()
        }
      });
    } else {
      // Agent-specific memory
      if (!agentId) {
        return NextResponse.json({ error: 'agentId required for agent memories' }, { status: 400 });
      }

      memory = await prisma.domainAgentMemory.upsert({
        where: {
          agentId_category_key: { agentId, category, key }
        },
        update: {
          content,
          confidence,
          importance,
          source,
          expiresAt: expiresAt ? new Date(expiresAt) : undefined,
          accessCount: { increment: 1 },
          updatedAt: new Date()
        },
        create: {
          id: `mem_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          agentId,
          category,
          key,
          content,
          confidence,
          importance,
          source,
          expiresAt: expiresAt ? new Date(expiresAt) : undefined,
          updatedAt: new Date()
        }
      });
    }

    return NextResponse.json({
      success: true,
      memory,
      scope
    });
  } catch (error: any) {
    console.error('Error creating memory:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

// DELETE - Remove memory
export async function DELETE(request: NextRequest) {
  try {
    const body = await request.json();
    const { id, agentId, category, key, scope = 'agent' } = body;

    if (scope === 'shared') {
      if (id) {
        await prisma.ghostMemory.delete({ where: { id } });
      } else if (category && key) {
        await prisma.ghostMemory.delete({
          where: { category_key: { category, key } }
        });
      }
    } else {
      if (id) {
        await prisma.domainAgentMemory.delete({ where: { id } });
      } else if (agentId && category && key) {
        await prisma.domainAgentMemory.delete({
          where: { agentId_category_key: { agentId, category, key } }
        });
      }
    }

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('Error deleting memory:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
