import { NextRequest, NextResponse } from 'next/server'
import { getTagsProvider, 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 || process.env.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 || process.env.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 GET(request: NextRequest) {
  try {
    const config = await getSystemConfig()
    const tagsProvider = getTagsProvider(config)
    const embeddingsProvider = getEmbeddingsProvider(config)

    const testText = 'test'

    // Test embeddings provider
    const embeddings = await embeddingsProvider.getEmbeddings(testText)

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

    const tagsProviderType = config.AI_PROVIDER_TAGS || 'ollama'
    const embeddingsProviderType = config.AI_PROVIDER_EMBEDDING || 'ollama'
    const details = getProviderDetails(config, embeddingsProviderType)

    return NextResponse.json({
      success: true,
      tagsProvider: tagsProviderType,
      embeddingsProvider: embeddingsProviderType,
      embeddingLength: embeddings.length,
      firstValues: embeddings.slice(0, 5),
      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',
        stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
        details
      },
      { status: 500 }
    )
  }
}
