import { NextRequest, NextResponse } from 'next/server'
import { chatCompletion, isHealthy } from '@/lib/ai/ollama'
import { db } from '@/lib/db'

const SYSTEM_PROMPT = `You are Studo-Guide AI, an intelligent career guidance and academic support assistant for South African students. You help learners from Grade 8 to post-matric with:
- Career guidance and subject selection
- Study tips and exam preparation (CAPS curriculum)
- Bursary and scholarship information
- University application guidance (SA universities)
- APS score calculation and advice
- Motivation and academic planning
- Tutor subject recommendations

You are knowledgeable about the South African education system including:
- All 9 provinces and their schools/universities
- CAPS curriculum subjects and requirements
- SA university admission requirements
- NSFAS and other bursary schemes
- SA career market trends

Always be encouraging, supportive, and practical. Use South African English conventions.`

export async function OPTIONS() {
  // Used by the client to check model health
  try {
    const healthy = await isHealthy()
    return NextResponse.json({ status: healthy ? 'online' : 'offline' }, { status: 200 })
  } catch {
    return NextResponse.json({ status: 'offline' }, { status: 503 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { messages: userMessages, userId } = body as {
      messages: Array<{ role: string; content: string }>
      userId?: string
    }

    if (!userMessages || !Array.isArray(userMessages) || userMessages.length === 0) {
      return NextResponse.json(
        { error: 'Please provide at least one message.' },
        { status: 400 }
      )
    }

    // Build the full message array with system prompt
    const allMessages = [
      { role: 'system' as const, content: SYSTEM_PROMPT },
      ...userMessages.map((m) => ({
        role: (m.role === 'user' ? 'user' : m.role === 'assistant' ? 'assistant' : 'user') as 'user' | 'assistant',
        content: m.content,
      })),
    ]

    // Call Ollama
    let response: string
    try {
      response = await chatCompletion(allMessages)
    } catch (aiError) {
      console.error('Ollama call failed:', aiError instanceof Error ? aiError.message : aiError)
      return NextResponse.json(
        {
          error:
            'The AI model is currently unavailable. It may be starting up — please try again in a moment.',
        },
        { status: 503 }
      )
    }

    // Estimate tokens (rough: ~4 chars per token)
    const tokensUsed = Math.ceil(response.length / 4) + Math.ceil(
      userMessages.reduce((sum, m) => sum + m.content.length, 0) / 4
    )

    // Save user message
    const lastUserMsg = userMessages[userMessages.length - 1]
    if (lastUserMsg && lastUserMsg.role === 'user') {
      try {
        await db.chatMessage.create({
          data: {
            userId: userId || 'anonymous',
            role: 'user',
            content: lastUserMsg.content,
            model: 'granite3.1-moe',
            tokensUsed: Math.ceil(lastUserMsg.content.length / 4),
          },
        })
      } catch {
        // Non-critical: log only
      }
    }

    // Save assistant response
    try {
      await db.chatMessage.create({
        data: {
          userId: userId || 'anonymous',
          role: 'assistant',
          content: response,
          model: 'granite3.1-moe',
          tokensUsed,
        },
      })
    } catch {
      // Non-critical: log only
    }

    return NextResponse.json({
      response,
      tokensUsed,
    })
  } catch (error) {
    console.error('Chat API error:', error instanceof Error ? error.message : error)
    return NextResponse.json(
      { error: 'An internal error occurred. Please try again.' },
      { status: 500 }
    )
  }
}
