import { NextRequest, NextResponse } from 'next/server';
import { adminDb } from '@/lib/firebase/admin';

export async function GET(request: NextRequest) {
  try {
    const projectId = request.nextUrl.searchParams.get('projectId');
    
    if (!projectId) {
      return NextResponse.json({ error: 'Missing projectId' }, { status: 400 });
    }

    // Get all conversations sorted by time
    const conversationsSnapshot = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorConversations')
      .orderBy('createdAt', 'asc')
      .get();

    const conversations = conversationsSnapshot.docs.map(doc => {
      const data = doc.data();
      return {
        name: data.name,
        createdAt: new Date(data.createdAt),
        score: data.relevanceScore || 0
      };
    });

    // Find NHL work sessions (negative scores clustered in time)
    const nhlConversations = conversations.filter(c => c.score < 0);
    
    return NextResponse.json({
      totalConversations: conversations.length,
      nhlConversations: nhlConversations.length,
      nhlDates: nhlConversations.map(c => ({
        date: c.createdAt.toISOString().split('T')[0],
        name: c.name
      })),
      // Find if NHL conversations cluster
      nhlDateCounts: nhlConversations.reduce((acc: any, c) => {
        const date = c.createdAt.toISOString().split('T')[0];
        acc[date] = (acc[date] || 0) + 1;
        return acc;
      }, {})
    });

  } catch (error) {
    console.error('Error analyzing session summary:', error);
    return NextResponse.json(
      { error: 'Failed to analyze', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

