import { NextResponse } from 'next/server';
import { GoogleGenAI } from '@google/genai';

export async function POST(request: Request) {
  try {
    const { schedule, completions } = await request.json();
    
    const apiKey = process.env.GEMINI_API_KEY;
    if (!apiKey) {
      return NextResponse.json({ error: 'GEMINI_API_KEY is not set in the environment variables.' }, { status: 400 });
    }

    const ai = new GoogleGenAI({ apiKey: apiKey });

    const prompt = `You are an expert productivity coach. 
I have a weekly schedule and a history of my task completions.

Here is a summary of my schedule (blocks):
${JSON.stringify(schedule)}

Here is a summary of my recent task completions:
${JSON.stringify(completions)}

Analyze this data and provide 3-4 personalized, highly specific productivity suggestions or insights.
Identify patterns (e.g., "You tend to miss your Web Dev blocks on Fridays", or "Your sleep is very low").
Provide actionable advice.

CRITICAL REQUIREMENT: You MUST provide your entire response in the Sinhala language (සිංහල). 
CRITICAL REQUIREMENT: You MUST return the response strictly in the following JSON format, without any markdown wrappers or codeblocks (no \`\`\`json):
{
  "greeting": "A friendly greeting and summary in Sinhala",
  "insights": [
    {
      "title": "Insight Title",
      "observation": "What you noticed",
      "advice": ["Actionable step 1", "Actionable step 2"]
    }
  ],
  "conclusion": "A concluding encouraging remark"
}`;

    const response = await ai.models.generateContent({
        model: 'gemini-2.5-flash',
        contents: prompt,
    });

    let text = response.text || '';
    text = text.replace(/```json/g, '').replace(/```/g, '').trim();

    return NextResponse.json({ data: JSON.parse(text) });
  } catch (error: Error | unknown) {
    console.error('AI Insight Error:', error);
    return NextResponse.json({ error: error instanceof Error ? error.message : 'Failed to generate insights' }, { status: 500 });
  }
}
