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

export const dynamic = 'force-dynamic';

/**
 * Proactive Context Retrieval API
 * 
 * Called at session start to fetch relevant memories based on:
 * - Keywords/topics mentioned
 * - High importance memories
 * - Recently updated memories
 * - Memories that haven't been accessed in a while (staleness check)
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { keywords = [], topic, includeStale = true, limit = 20 } = body;

    // Build search conditions
    const searchConditions: Record<string, unknown>[] = [];

    // 1. High importance memories (always include)
    searchConditions.push({
      importance: { gte: 8 },
      isActive: true,
    });

    // 2. Keyword-based search
    if (keywords.length > 0) {
      for (const keyword of keywords) {
        searchConditions.push({
          OR: [
            { key: { contains: keyword, mode: 'insensitive' } },
            { value: { contains: keyword, mode: 'insensitive' } },
            { context: { contains: keyword, mode: 'insensitive' } },
          ],
          isActive: true,
        });
      }
    }

    // 3. Topic-based search
    if (topic) {
      searchConditions.push({
        OR: [
          { key: { contains: topic, mode: 'insensitive' } },
          { value: { contains: topic, mode: 'insensitive' } },
          { category: { contains: topic, mode: 'insensitive' } },
        ],
        isActive: true,
      });
    }

    // Fetch relevant memories
    const relevantMemories = await prisma.tesaMemory.findMany({
      where: {
        OR: searchConditions.length > 0 ? searchConditions : [{ isActive: true }],
      },
      orderBy: [
        { importance: 'desc' },
        { updatedAt: 'desc' },
      ],
      take: limit,
    });

    // 4. Find stale items (not accessed in 30+ days, might need attention)
    let staleItems: typeof relevantMemories = [];
    if (includeStale) {
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

      staleItems = await prisma.tesaMemory.findMany({
        where: {
          isActive: true,
          importance: { gte: 5 },
          OR: [
            { lastAccessed: { lt: thirtyDaysAgo } },
            { lastAccessed: null },
          ],
          updatedAt: { lt: thirtyDaysAgo },
        },
        orderBy: { importance: 'desc' },
        take: 5,
      });
    }

    // 5. Get recent insights
    const recentInsights = await prisma.tesaMemory.findMany({
      where: {
        category: 'insight',
        isActive: true,
        createdAt: { gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) }, // Last 7 days
      },
      orderBy: { createdAt: 'desc' },
      take: 5,
    });

    // Update access stats for retrieved memories
    const allIds = [
      ...relevantMemories.map((m: any) => m.id),
      ...staleItems.map((m: any) => m.id),
      ...recentInsights.map((m: any) => m.id),
    ];
    
    if (allIds.length > 0) {
      await prisma.tesaMemory.updateMany({
        where: { id: { in: allIds } },
        data: {
          lastAccessed: new Date(),
          accessCount: { increment: 1 },
        },
      });
    }

    // Build context summary
    const contextSummary = {
      totalMemories: await prisma.tesaMemory.count({ where: { isActive: true } }),
      highPriorityCount: relevantMemories.filter((m: any) => m.importance >= 8).length,
      staleCount: staleItems.length,
      recentInsightsCount: recentInsights.length,
    };

    return NextResponse.json({
      success: true,
      context: {
        relevantMemories: relevantMemories.map((m: any) => ({
          id: m.id,
          category: m.category,
          key: m.key,
          value: m.value,
          context: m.context,
          importance: m.importance,
          tags: m.tags,
        })),
        staleItems: staleItems.map((m: any) => ({
          id: m.id,
          key: m.key,
          value: m.value,
          lastAccessed: m.lastAccessed,
          updatedAt: m.updatedAt,
        })),
        recentInsights: recentInsights.map((m: any) => ({
          id: m.id,
          key: m.key,
          value: m.value,
          createdAt: m.createdAt,
        })),
        summary: contextSummary,
      },
    });
  } catch (error) {
    console.error('Error fetching Tesa context:', error);
    return NextResponse.json(
      { error: 'Failed to fetch context' },
      { status: 500 }
    );
  }
}
