import { NextRequest, NextResponse } from 'next/server';
import { generateInsights, saveInsightsAsMemories, generateLLMInsights, InsightResult } from '@/lib/tesa/insights';

export const dynamic = 'force-dynamic';

/**
 * Insight Generation API
 * 
 * GET - Generate and return insights (without saving)
 * POST - Generate, save as memories, and return insights
 */

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const includeLLM = searchParams.get('llm') === 'true';

    // Generate rule-based insights
    const ruleBasedInsights = await generateInsights();

    // Optionally generate LLM insights
    let llmInsights: InsightResult[] = [];
    if (includeLLM) {
      llmInsights = await generateLLMInsights();
    }

    const allInsights = [...ruleBasedInsights, ...llmInsights];

    // Sort by importance
    allInsights.sort((a, b) => b.importance - a.importance);

    return NextResponse.json({
      success: true,
      insights: allInsights,
      stats: {
        total: allInsights.length,
        ruleBasedCount: ruleBasedInsights.length,
        llmCount: llmInsights.length,
        byType: {
          pattern: allInsights.filter(i => i.type === 'pattern').length,
          gap: allInsights.filter(i => i.type === 'gap').length,
          connection: allInsights.filter(i => i.type === 'connection').length,
          suggestion: allInsights.filter(i => i.type === 'suggestion').length,
          stale: allInsights.filter(i => i.type === 'stale').length,
        },
        actionableCount: allInsights.filter(i => i.actionable).length,
      },
    });
  } catch (error) {
    console.error('Error generating insights:', error);
    return NextResponse.json(
      { error: 'Failed to generate insights' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { includeLLM = false, save = true } = body;

    // Generate rule-based insights
    const ruleBasedInsights = await generateInsights();

    // Optionally generate LLM insights
    let llmInsights: InsightResult[] = [];
    if (includeLLM) {
      llmInsights = await generateLLMInsights();
    }

    const allInsights = [...ruleBasedInsights, ...llmInsights];

    // Sort by importance
    allInsights.sort((a, b) => b.importance - a.importance);

    // Save insights as memories if requested
    let savedCount = 0;
    if (save) {
      savedCount = await saveInsightsAsMemories(allInsights);
    }

    return NextResponse.json({
      success: true,
      insights: allInsights,
      saved: savedCount,
      stats: {
        total: allInsights.length,
        ruleBasedCount: ruleBasedInsights.length,
        llmCount: llmInsights.length,
        savedAsMemories: savedCount,
      },
    });
  } catch (error) {
    console.error('Error generating/saving insights:', error);
    return NextResponse.json(
      { error: 'Failed to generate insights' },
      { status: 500 }
    );
  }
}
