import { NextRequest, NextResponse } from 'next/server'
import { chatCompletion } from '@/lib/ai/ollama'
import { fetchBursaries, fetchUniversityInfo, fetchCareerInfo } from '@/lib/ai/browse'
import { db } from '@/lib/db'

interface SmartMatchRequest {
  userId?: string
  profile?: {
    grade?: number
    province?: string
    subjects?: string[]
    careerInterests?: string
    averageMark?: number
  }
}

export async function POST(request: NextRequest) {
  try {
    const body: SmartMatchRequest = await request.json()
    const { userId, profile } = body

    // If userId is provided, try to get profile from DB
    let userProfile = profile
    if (userId && !profile) {
      try {
        const user = await db.user.findUnique({
          where: { id: userId },
        })
        if (user) {
          userProfile = {
            grade: user.grade ?? undefined,
            province: user.province ?? undefined,
            subjects: user.subjectsStruggling ? JSON.parse(user.subjectsStruggling) : undefined,
            careerInterests: user.careerInterests ?? undefined,
          }
        }
      } catch {
        // Continue with whatever profile we have
      }
    }

    // Fetch data from multiple sources in parallel
    const [bursaries, universities, careers] = await Promise.allSettled([
      fetchBursaries(),
      fetchUniversityInfo(),
      fetchCareerInfo(),
    ])

    const bursaryData = bursaries.status === 'fulfilled' ? bursaries.value : []
    const universityData = universities.status === 'fulfilled' ? universities.value : []
    const careerData = careers.status === 'fulfilled' ? careers.value : []

    // Build context for AI analysis
    const context = `
Student Profile:
- Grade: ${userProfile?.grade || 'Not specified'}
- Province: ${userProfile?.province || 'Not specified'}
- Subjects: ${userProfile?.subjects?.join(', ') || 'Not specified'}
- Career Interests: ${userProfile?.careerInterests || 'Not specified'}
- Average Mark: ${userProfile?.averageMark ? `${userProfile.averageMark}%` : 'Not specified'}

Available Bursaries (${bursaryData.length} found):
${bursaryData.slice(0, 10).map((b, i) => `${i + 1}. ${b.title} - ${b.snippet || b.description?.slice(0, 100)}`).join('\n')}

Available Universities (${universityData.length} found):
${universityData.slice(0, 8).map((u, i) => `${i + 1}. ${u.name} - ${u.snippet || u.description?.slice(0, 100)}`).join('\n')}

Career Information (${careerData.length} found):
${careerData.slice(0, 8).map((c, i) => `${i + 1}. ${c.title} - ${c.snippet}`).join('\n')}
`.trim()

    const systemPrompt = `You are Studo-Guide AI Smart Match. Based on the student profile and available data, provide personalized recommendations.
Analyze the student's profile and match them with the most relevant opportunities.

Respond in JSON format with the following structure:
{
  "summary": "A brief encouraging summary (2-3 sentences)",
  "bursaries": [{"title": "...", "reason": "Why this matches", "priority": "high/medium/low"}],
  "universities": [{"name": "...", "reason": "Why this matches", "priority": "high/medium/low"}],
  "careers": [{"title": "...", "reason": "Why this matches", "priority": "high/medium/low"}],
  "studyTips": ["tip1", "tip2", "tip3"],
  "nextSteps": ["step1", "step2", "step3"]
}

Limit to top 5 for each category. Be specific and practical. Use South African context.`

    let aiResponse: string
    try {
      aiResponse = await chatCompletion(
        [
          { role: 'system', content: systemPrompt },
          { role: 'user', content: context },
        ],
        undefined,
        { temperature: 0.4 }
      )
    } catch (aiError) {
      console.error('Smart match AI call failed:', aiError instanceof Error ? aiError.message : aiError)
      return NextResponse.json(
        { error: 'AI model is currently unavailable. Please try again later.' },
        { status: 503 }
      )
    }

    // Parse AI response
    let recommendations
    try {
      let jsonStr = aiResponse.trim()
      const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/)
      if (jsonMatch) {
        jsonStr = jsonMatch[1].trim()
      }
      recommendations = JSON.parse(jsonStr)
    } catch {
      // If parsing fails, return raw response
      recommendations = {
        summary: aiResponse.slice(0, 300),
        bursaries: [],
        universities: [],
        careers: [],
        studyTips: [],
        nextSteps: [],
      }
    }

    return NextResponse.json({
      success: true,
      profile: userProfile,
      recommendations,
      dataSourceCounts: {
        bursaries: bursaryData.length,
        universities: universityData.length,
        careers: careerData.length,
      },
      generatedAt: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Smart match error:', error instanceof Error ? error.message : error)
    return NextResponse.json(
      { error: 'Failed to generate smart match recommendations.' },
      { status: 500 }
    )
  }
}
