import { NextRequest, NextResponse } from "next/server";
import { GoogleGenAI } from "@google/genai";

const VERTEX_AI_MODEL = process.env.VERTEX_AI_MODEL || 'gemini-3-pro-preview';
const VERTEX_PROJECT_ID = process.env.VERTEX_AI_PROJECT_ID || 'gen-lang-client-0980079410';
const VERTEX_LOCATION = process.env.VERTEX_AI_LOCATION || 'global';

const genAI = new GoogleGenAI({
  project: VERTEX_PROJECT_ID,
  location: VERTEX_LOCATION,
  vertexai: true,
});

export async function POST(request: NextRequest) {
  try {
    const { content, title } = await request.json();

    if (!content) {
      return NextResponse.json({ error: "Content is required" }, { status: 400 });
    }

    // Truncate content if it's too long (Gemini has token limits)
    const maxContentLength = 30000; // ~30k characters
    const truncatedContent = content.length > maxContentLength 
      ? content.substring(0, maxContentLength) + "..." 
      : content;

    const prompt = `Read this document titled "${title}" and provide a concise 1-2 sentence summary that captures the main topic and key points. Be specific and actionable.

Document content:
${truncatedContent}

Summary:`;

    const result = await genAI.models.generateContent({
      model: VERTEX_AI_MODEL,
      contents: [{
        role: 'user',
        parts: [{ text: prompt }],
      }],
      config: {
        temperature: 0.3, // Lower temperature for consistent summaries
      },
    });
    
    const summary = result.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || 'Summary unavailable';

    return NextResponse.json({ summary });
  } catch (error) {
    console.error("Error generating summary:", error);
    return NextResponse.json(
      {
        error: "Failed to generate summary",
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

