/**
 * Context retrieval — ai-assistant.
 *
 * Embeds the user query, queries the tenant's Vectorize namespace (topK=8),
 * and returns the concatenated matching chunk texts for system prompt injection.
 */
import type { Env } from '@zync/types'
import { embedText } from './embed'

/**
 * Retrieve the top-8 relevant document chunks for a query from the tenant's
 * Vectorize namespace (`tenant:{tenantId}`).
 *
 * Returns `''` (empty string, not an error) when the namespace is empty or
 * no matches are found — chat still works for new tenants with no indexed data.
 */
export async function retrieveContext(
  env: Env,
  tenantId: string,
  query: string,
): Promise<string> {
  try {
    const vector = await embedText(env, query)
    const results = await env.VECTORIZE.query(vector, {
      namespace: `tenant:${tenantId}`,
      topK: 8,
      returnMetadata: true,
    })

    const chunks = results.matches
      .map((m) => (m.metadata as Record<string, unknown> | undefined)?.['text'] as string | undefined)
      .filter((t): t is string => typeof t === 'string' && t.length > 0)

    return chunks.join('\n\n---\n\n')
  } catch (err) {
    // Namespace not found or empty → graceful empty context
    const errMsg = err instanceof Error ? err.message : String(err)
    // Vectorize throws when namespace doesn't exist; treat as empty
    if (
      errMsg.includes('namespace not found') ||
      errMsg.includes('does not exist') ||
      errMsg.includes('not found')
    ) {
      return ''
    }
    throw err
  }
}
