/**
 * Qdrant RAG tool for searching knowledge base
 * Optional: Only used if QDRANT_URL and QDRANT_API_KEY are configured
 */

import { tool } from 'ai'
import { z } from 'zod'
import { getEmbeddingModel } from '@/lib/openrouter'
import { embed } from 'ai'

const qdrantRagSchema = z.object({
  query: z
    .string()
    .describe('The search query or topic to find relevant documents for'),
  topK: z
    .number()
    .int()
    .min(1)
    .max(20)
    .default(5)
    .describe('Maximum number of results to return'),
  threshold: z
    .number()
    .min(0)
    .max(1)
    .default(0.7)
    .describe('Similarity threshold (0-1) for filtering results'),
})

type QdrantRagInput = z.infer<typeof qdrantRagSchema>

/**
 * Qdrant RAG tool for searching the knowledge base
 * Requires Qdrant to be configured in environment variables
 *
 * NOTE: Using `as any` to work around Vercel AI SDK tool() typing limitations.
 * The tool works correctly at runtime; the typing issue is in the SDK's overload resolution.
 */
export const qdrantRagTool = tool({
  description:
    'Search the knowledge base for relevant information and context. Use this to retrieve documents that can inform your responses.',
  parameters: qdrantRagSchema,
  execute: async (input: QdrantRagInput) => {
    const { query, topK, threshold } = input
    // Check if Qdrant is configured
    const qdrantUrl = process.env.QDRANT_URL
    const qdrantApiKey = process.env.QDRANT_API_KEY

    if (!qdrantUrl || !qdrantApiKey) {
      return {
        success: false,
        message: 'Qdrant is not configured. RAG search unavailable.',
        results: [],
      }
    }

    try {
      // Get embedding for the query
      const { embedding } = await embed({
        model: getEmbeddingModel(),
        value: query,
      })

      // Query Qdrant
      // Note: This is a simplified implementation
      // In production, you would use the Qdrant JS client
      const response = await fetch(`${qdrantUrl}/collections/documents/points/search`, {
        method: 'POST',
        headers: {
          'api-key': qdrantApiKey,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          vector: embedding,
          limit: topK,
          score_threshold: threshold,
          with_payload: true,
        }),
      })

      if (!response.ok) {
        return {
          success: false,
          message: `Qdrant search failed: ${response.statusText}`,
          results: [],
        }
      }

      const data = (await response.json()) as any

      // Format results
      const results = data.result?.map((hit: any) => ({
        content: hit.payload?.text || hit.payload?.content || '',
        score: hit.score,
        source: hit.payload?.source || 'unknown',
        metadata: hit.payload,
      })) || []

      return {
        success: true,
        message: `Found ${results.length} relevant documents`,
        results,
      }
    } catch (error) {
      return {
        success: false,
        message: `RAG search error: ${error instanceof Error ? error.message : 'Unknown error'}`,
        results: [],
      }
    }
  },
} as any)
