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

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

const SYSTEM_PROMPT = `You are SentinelScan, an elite application security analyst specializing in the OWASP Top 10.
You receive source code and produce a structured JSON vulnerability report.

Analyze the code for security vulnerabilities. For each finding, return:
- id: sequential string like "VULN-001"
- severity: "CRITICAL" | "HIGH" | "MEDIUM" | "LOW" | "INFO"
- category: OWASP category (e.g., "A01:2021 - Broken Access Control")
- title: concise vulnerability title
- line: approximate line number (integer) or null if not applicable
- description: 2-3 sentence explanation of the vulnerability
- remediation: specific code fix suggestion

Also include:
- summary: 1-2 sentence overall assessment
- score: security score 0-100 (100 = perfect)
- language: detected programming language

Respond ONLY with valid JSON in this exact format:
{
  "summary": "...",
  "score": 85,
  "language": "JavaScript",
  "findings": [
    {
      "id": "VULN-001",
      "severity": "HIGH",
      "category": "A03:2021 - Injection",
      "title": "SQL Injection via string concatenation",
      "line": 15,
      "description": "...",
      "remediation": "..."
    }
  ]
}

If the code is secure, return an empty findings array with a high score.
Be thorough but precise — no false positives. Focus on real, exploitable issues.`;

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

    if (!code || typeof code !== 'string' || code.trim().length < 10) {
      return NextResponse.json({ error: 'Please provide at least 10 characters of code.' }, { status: 400 });
    }

    if (code.length > 50000) {
      return NextResponse.json({ error: 'Code exceeds 50,000 character limit.' }, { status: 400 });
    }

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

    const response = await fetch('https://routellm.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 code for security vulnerabilities:\n\n\`\`\`\n${code}\n\`\`\`` },
        ],
        temperature: 0.1,
        max_tokens: 4000,
      }),
    });

    if (!response.ok) {
      const errText = await response.text();
      console.error('LLM API error:', errText);
      return NextResponse.json({ error: 'Analysis service unavailable.' }, { status: 502 });
    }

    const data = await response.json();
    const content = data.choices?.[0]?.message?.content || '';

    // Extract JSON from response (handle markdown code fences)
    const jsonMatch = content.match(/```(?:json)?\s*([\s\S]*?)```/) || [null, content];
    const jsonStr = (jsonMatch[1] || content).trim();

    const report = JSON.parse(jsonStr);
    return NextResponse.json(report);
  } catch (error) {
    console.error('SentinelScan error:', error);
    return NextResponse.json({ error: 'Failed to analyze code.' }, { status: 500 });
  }
}
