import { NextRequest, NextResponse } from 'next/server'
import Anthropic from '@anthropic-ai/sdk'

export const runtime = 'nodejs'

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const featureName: string = body.featureName || 'Custom Feature'
    const description: string = body.description || ''
    const requirements: string[] = Array.isArray(body.requirements) ? body.requirements : []
    const projectType: string | undefined = body.projectType

    const apiKey =
      process.env.ANTHROPIC_API_KEY ||
      process.env.REACT_APP_ANTHROPIC_API_KEY ||
      process.env.NEXT_PUBLIC_ANTHROPIC_API_KEY ||
      ''

    if (!apiKey) {
      return NextResponse.json(
        { success: false, message: 'Missing Anthropic API key in env' },
        { status: 500 }
      )
    }

    const anthropic = new Anthropic({ apiKey })

    const requirementsText = (requirements || [])
      .filter((r) => r && r.trim())
      .map((r) => `- ${r}`)
      .join('\n')

    const prompt = `
Analyze this feature and provide complexity assessment and business logic rules:

Project Type: ${projectType || 'Generic'}
Feature Name: ${featureName}
Description: ${description}

Requirements:
${requirementsText}

Based on these requirements, provide a JSON response with:
1. Complexity level (low/medium/high)
2. Business logic rules that should be implemented

Complexity Guidelines:
- LOW: Simple CRUD operations, basic display features
- MEDIUM: Moderate business logic, some validations, basic integrations
- HIGH: Complex business rules, security requirements, external integrations, compliance needs

Return ONLY a JSON object in this exact format:
{
  "complexity": "low|medium|high",
  "logicRules": [
    "Business rule 1 based on requirements",
    "Business rule 2 based on requirements",
    "Business rule 3 based on requirements"
  ]
}`

    const message = await anthropic.messages.create({
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 1000,
      temperature: 0.2,
      messages: [{ role: 'user', content: prompt }],
    })

    const responseText = (message as any).content?.[0]?.text?.trim?.() || ''
    const jsonMatch = responseText.match(/\{[\s\S]*\}/)
    if (!jsonMatch) {
      return NextResponse.json(
        { success: false, message: 'Invalid AI response format' },
        { status: 502 }
      )
    }

    const parsed = JSON.parse(jsonMatch[0])
    // Use the user-selected complexity if provided, otherwise use AI's suggestion
    const complexity = (body.complexity || parsed.complexity as 'low' | 'medium' | 'high') || 'medium'
    const logicRules = Array.isArray(parsed.logicRules) ? parsed.logicRules : []

    return NextResponse.json({ success: true, data: { complexity, logicRules } })
  } catch (error: any) {
    return NextResponse.json(
      { success: false, message: error?.message || 'AI analysis failed' },
      { status: 500 }
    )
  }
}

