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

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

const SYSTEM_PROMPT = `You are DissertationReady, an elite academic peer reviewer.
You receive a dissertation/thesis excerpt and produce a structured review.

Evaluate the submission across these dimensions:
1. Thesis Clarity — Is the central argument/hypothesis clear and defensible?
2. Methodology Rigor — Is the research design sound? Are methods appropriate?
3. Literature Coverage — Does it engage with key prior work? Any gaps?
4. Argument Structure — Is the logical flow coherent? Are claims supported?
5. Evidence Quality — Are data/sources credible and sufficient?
6. Writing Quality — Academic tone, grammar, clarity, conciseness
7. Citation & Formatting — Are references adequate? Any red flags?
8. Originality — Does this contribute something new to the field?

For each dimension, provide:
- score: 1-10
- verdict: "PASS" | "NEEDS_WORK" | "FAIL" 
- feedback: 2-3 sentences of specific, actionable feedback

Also provide:
- overallScore: weighted average 1-100
- overallVerdict: "READY_TO_SUBMIT" | "REVISIONS_NEEDED" | "MAJOR_REVISIONS" | "NOT_READY"
- summary: 3-4 sentence executive summary
- topStrengths: array of 2-3 strings
- criticalIssues: array of 0-3 strings (empty if none)
- detectedField: detected academic field/discipline

Respond ONLY with valid JSON:
{
  "overallScore": 75,
  "overallVerdict": "REVISIONS_NEEDED",
  "summary": "...",
  "detectedField": "Computer Science",
  "topStrengths": ["..."],
  "criticalIssues": ["..."],
  "dimensions": [
    { "name": "Thesis Clarity", "score": 8, "verdict": "PASS", "feedback": "..." }
  ]
}

Be rigorous but constructive. An academic career may depend on this review.`;

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

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

    if (text.length > 80000) {
      return NextResponse.json({ error: 'Text exceeds 80,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 userMsg = `Review this ${field ? field + ' ' : ''}dissertation${title ? ` titled "${title}"` : ''}:\n\n${text}`;

    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: userMsg },
        ],
        temperature: 0.2,
        max_tokens: 4000,
      }),
    });

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

    const data = await response.json();
    const content = data.choices?.[0]?.message?.content || '';
    const jsonMatch = content.match(/```(?:json)?\s*([\s\S]*?)```/) || [null, content];
    const report = JSON.parse((jsonMatch[1] || content).trim());
    return NextResponse.json(report);
  } catch (error) {
    console.error('DissertationReady error:', error);
    return NextResponse.json({ error: 'Failed to review submission.' }, { status: 500 });
  }
}
