import { NextRequest, NextResponse } from 'next/server'; import { GoogleGenerativeAI } from '@google/generative-ai'; export async function POST(request: NextRequest) { try { const { role, difficulty, evaluations, questions, answers } = await request.json(); const headerApiKey = request.headers.get('x-gemini-api-key'); const apiKey = headerApiKey || process.env.GEMINI_API_KEY; if (!apiKey) { return NextResponse.json( { error: 'GEMINI_API_KEY is not configured. Please add it in Settings or .env.local file.' }, { status: 500 } ); } const genAI = new GoogleGenerativeAI(apiKey); const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }); const qaDetails = questions.map((q: { text: string }, i: number) => { const answer = answers[i]?.text || 'No answer provided'; const evaluation = evaluations[i]; return `Q${i + 1}: ${q.text}\nAnswer: ${answer}\nScore: ${evaluation?.score || 0}/10`; }).join('\n\n'); const avgScore = evaluations.length > 0 ? evaluations.reduce((sum: number, e: { score: number }) => sum + e.score, 0) / evaluations.length : 0; const prompt = `You are a senior interview coach reviewing a complete mock interview session. ROLE: ${role} DIFFICULTY: ${difficulty} AVERAGE SCORE: ${avgScore.toFixed(1)}/10 INTERVIEW DETAILS: ${qaDetails} Generate a comprehensive session summary. Return ONLY valid JSON (no markdown, no code blocks): { "totalScore": , "averageScore": , "strengths": [], "weaknesses": [], "recommendations": [], "categoryScores": [], "overallFeedback": "" } Be constructive, specific, and encouraging. Focus on actionable improvement paths.`; const result = await model.generateContent(prompt); const responseText = result.response.text(); const jsonMatch = responseText.match(/\{[\s\S]*\}/); if (!jsonMatch) { throw new Error('Failed to parse summary from AI response'); } const summary = JSON.parse(jsonMatch[0]); summary.totalQuestions = questions.length; summary.answeredQuestions = answers.length; return NextResponse.json({ summary }); } catch (error) { console.error('Error generating summary:', error); return NextResponse.json( { error: 'Failed to generate session summary.' }, { status: 500 } ); } }