File size: 2,751 Bytes
a0da743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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": <total score out of ${evaluations.length * 10}>,
  "averageScore": <average score to 1 decimal>,
  "strengths": [<array of 3-4 key strengths demonstrated across all answers>],
  "weaknesses": [<array of 3-4 main areas needing improvement>],
  "recommendations": [<array of 4-5 specific, actionable study/practice recommendations>],
  "categoryScores": [<array of {"category": "topic", "score": average_score_for_topic}>],
  "overallFeedback": "<a motivating 3-4 sentence overall assessment with encouragement and next steps>"
}

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 }
    );
  }
}