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

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

const SYSTEM_PROMPT = `You are ContractCraft, an AI legal document analyst.
You receive contract or legal document text and produce a structured JSON analysis.

Extract and analyze:
1. Key parties involved
2. Important dates and deadlines
3. Financial terms (payment amounts, penalties, etc.)
4. Obligations for each party
5. Risk flags (ambiguous clauses, missing protections, unfavorable terms)
6. Termination conditions

Respond ONLY with valid JSON in this exact format:
{
  "summary": "1-2 sentence overview of the document",
  "documentType": "NDA | Service Agreement | Employment Contract | Lease | Other",
  "parties": [{"name": "...", "role": "..."}],
  "keyDates": [{"date": "...", "description": "...", "urgency": "high|medium|low"}],
  "financialTerms": [{"item": "...", "amount": "...", "frequency": "..."}],
  "obligations": [{"party": "...", "obligation": "...", "deadline": "..."}],
  "riskFlags": [{"severity": "HIGH|MEDIUM|LOW", "clause": "...", "risk": "...", "recommendation": "..."}],
  "terminationConditions": ["..."],
  "overallRisk": 1-10,
  "recommendation": "1-2 sentence recommendation"
}`;

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 contract text.' }, { 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: `Analyze this document:\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('[ContractCraft]', err);
    return NextResponse.json({ error: 'Internal error.' }, { status: 500 });
  }
}
