import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';
export const maxDuration = 60;

const SYSTEM_PROMPT = `You are MeetingMind, an AI meeting notes analyst.
You receive raw meeting notes or transcripts and produce structured, actionable minutes.

Extract and organize:
1. Meeting metadata (topic, participants if mentioned, date if mentioned)
2. Key decisions made
3. Action items with owners and deadlines
4. Discussion highlights / important points
5. Open questions that need follow-up
6. Next steps

Respond ONLY with valid JSON in this exact format:
{
  "title": "inferred meeting title",
  "participants": ["name1", "name2"],
  "duration": "estimated if mentioned",
  "summary": "2-3 sentence executive summary",
  "decisions": [{"decision": "...", "context": "..."}],
  "actionItems": [{"task": "...", "owner": "...", "deadline": "...", "priority": "high|medium|low"}],
  "highlights": [{"topic": "...", "detail": "..."}],
  "openQuestions": ["..."],
  "nextSteps": ["..."],
  "sentiment": "positive|neutral|mixed|tense",
  "followUpDate": "suggested follow-up date or null"
}`;

export async function POST(req: NextRequest) {
  try {
    const { text } = await req.json();
    if (!text || typeof text !== 'string' || text.trim().length < 20) {
      return NextResponse.json({ error: 'Please provide at least 20 characters of meeting notes.' }, { status: 400 });
    }

    const apiKey = process.env.ABACUSAI_API_KEY;
    if (!apiKey) {
      return NextResponse.json({ error: 'LLM API not configured.' }, { status: 500 });
    }

    const response = await fetch('https://api.abacus.ai/v1/chat/completions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
      body: JSON.stringify({
        model: 'claude-sonnet-4-20250514',
        messages: [
          { role: 'system', content: SYSTEM_PROMPT },
          { role: 'user', content: `Process these meeting notes:\n\n${text.slice(0, 8000)}` },
        ],
        temperature: 0.2,
        max_tokens: 3000,
      }),
    });

    if (!response.ok) {
      return NextResponse.json({ error: 'AI analysis failed.' }, { status: 502 });
    }

    const data = await response.json();
    const content = data.choices?.[0]?.message?.content || '';
    const jsonMatch = content.match(/\{[\s\S]*\}/);
    if (!jsonMatch) {
      return NextResponse.json({ error: 'Failed to parse analysis.' }, { status: 500 });
    }

    return NextResponse.json(JSON.parse(jsonMatch[0]));
  } catch (err) {
    console.error('[MeetingMind]', err);
    return NextResponse.json({ error: 'Internal error.' }, { status: 500 });
  }
}
