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 workspace metadata
    const workspaceMetaDoc = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorData')
      .doc('workspace-meta')
      .get();

    const workspaceMeta = workspaceMetaDoc.exists ? workspaceMetaDoc.data() : null;

    // Get all conversations
    const conversationsSnapshot = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorConversations')
      .get();

    // Analyze by score
    const negative = conversationsSnapshot.docs
      .map(doc => ({ name: doc.data().name, score: doc.data().relevanceScore || 0 }))
      .filter(c => c.score < 0)
      .sort((a, b) => a.score - b.score);

    const positive = conversationsSnapshot.docs
      .map(doc => ({ name: doc.data().name, score: doc.data().relevanceScore || 0 }))
      .filter(c => c.score > 0)
      .sort((a, b) => b.score - a.score);

    const neutral = conversationsSnapshot.docs
      .filter(doc => (doc.data().relevanceScore || 0) === 0)
      .length;

    return NextResponse.json({
      workspacePath: workspaceMeta?.workspacePath,
      githubUrl: workspaceMeta?.githubUrl,
      workspaceFilesCount: workspaceMeta?.workspaceFiles?.length || 0,
      workspaceFilesSample: (workspaceMeta?.workspaceFiles || []).slice(0, 20),
      totalGenerations: workspaceMeta?.totalGenerations || 0,
      totalConversations: conversationsSnapshot.size,
      scoreBreakdown: {
        negative: negative.length,
        neutral,
        positive: positive.length
      },
      negativeScoreConversations: negative,
      topPositiveConversations: positive.slice(0, 10),
      sampleNeutralConversations: conversationsSnapshot.docs
        .filter(doc => (doc.data().relevanceScore || 0) === 0)
        .slice(0, 10)
        .map(doc => doc.data().name)
    });

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

