import { NextRequest, NextResponse } from 'next/server'
import { getEmbeddingsProvider } from '@/lib/ai/factory'
import { getSystemConfig } from '@/lib/config'

function getProviderDetails(config: Record<string, string>, providerType: string) {
  const provider = providerType.toLowerCase()

  switch (provider) {
    case 'ollama':
      return {
        provider: 'Ollama',
        baseUrl: config.OLLAMA_BASE_URL || 'http://localhost:11434',
        model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest'
      }
    case 'openai':
      return {
        provider: 'OpenAI',
        baseUrl: 'https://api.openai.com/v1',
        model: config.AI_MODEL_EMBEDDING || 'text-embedding-3-small'
      }
    case 'custom':
      return {
        provider: 'Custom OpenAI',
        baseUrl: config.CUSTOM_OPENAI_BASE_URL || 'Not configured',
        model: config.AI_MODEL_EMBEDDING || 'text-embedding-3-small'
      }
    default:
      return {
        provider: provider,
        baseUrl: 'unknown',
        model: config.AI_MODEL_EMBEDDING || 'unknown'
      }
  }
}

export async function POST(request: NextRequest) {
  try {
    const config = await getSystemConfig()
    const provider = getEmbeddingsProvider(config)

    const testText = 'test'
    const startTime = Date.now()
    const embeddings = await provider.getEmbeddings(testText)
    const endTime = Date.now()

    if (!embeddings || embeddings.length === 0) {
      const providerType = config.AI_PROVIDER_EMBEDDING || 'ollama'
      const details = getProviderDetails(config, providerType)
      return NextResponse.json(
        {
          success: false,
          error: 'No embeddings returned',
          provider: providerType,
          model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest',
          details
        },
        { status: 500 }
      )
    }

    const providerType = config.AI_PROVIDER_EMBEDDING || 'ollama'
    const details = getProviderDetails(config, providerType)

    return NextResponse.json({
      success: true,
      provider: providerType,
      model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest',
      embeddingLength: embeddings.length,
      firstValues: embeddings.slice(0, 5),
      responseTime: endTime - startTime,
      details
    })
  } catch (error: any) {
    const config = await getSystemConfig()
    const providerType = config.AI_PROVIDER_EMBEDDING || 'ollama'
    const details = getProviderDetails(config, providerType)

    return NextResponse.json(
      {
        success: false,
        error: error.message || 'Unknown error',
        provider: providerType,
        model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest',
        details,
        stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
      },
      { status: 500 }
    )
  }
}
