/**
 * GFS RAG Retriever
 * 
 * The main retrieval interface for the RAG system.
 * Agents call this to get grounded business context before making decisions.
 * 
 * Standing Order (RAG mandate): "Always check RAG for business rules before acting."
 */

import { vectorStore } from './vector-store';
import { ingestBusinessDocuments } from './ingest';
import { RAGContext, RAGConfig, RAGSearchResult, DEFAULT_RAG_CONFIG, SENSITIVE_CATEGORIES } from './types';

/**
 * Retrieve relevant business context for a query.
 * This is the primary function agents use to ground their decisions.
 * 
 * Safety:
 * - Automatically ingests documents on first call
 * - Filters sensitive categories unless explicitly requested
 * - Never returns content that enables data deletion
 * - Adds source citations for auditability
 */
export function retrieveContext(
  query: string,
  config?: Partial<RAGConfig>
): RAGContext {
  // Ensure documents are ingested
  ingestBusinessDocuments();

  const results = vectorStore.search(query, config);

  if (results.length === 0) {
    return {
      contextText: '[RAG] No relevant business context found for this query.',
      citations: [],
      chunkCount: 0,
      query,
      retrievedAt: new Date().toISOString(),
    };
  }

  // Build context text with citations
  const contextParts: string[] = [
    '=== RETRIEVED BUSINESS CONTEXT (RAG) ===',
    `Query: "${query}"`,
    `Sources: ${results.length} chunks retrieved`,
    '',
  ];

  const citations: RAGContext['citations'] = [];
  const seenSources = new Set<string>();

  for (let i = 0; i < results.length; i++) {
    const { chunk, score } = results[i];

    contextParts.push(`--- [${i + 1}] ${chunk.title} (${chunk.category}) [score: ${score.toFixed(2)}] ---`);
    contextParts.push(chunk.content);
    contextParts.push('');

    if (!seenSources.has(chunk.source)) {
      citations.push({
        source: chunk.source,
        title: chunk.title,
        category: chunk.category,
      });
      seenSources.add(chunk.source);
    }
  }

  contextParts.push('=== END RETRIEVED CONTEXT ===');
  contextParts.push('IMPORTANT: Cite these sources in your response where relevant.');

  return {
    contextText: contextParts.join('\n'),
    citations,
    chunkCount: results.length,
    query,
    retrievedAt: new Date().toISOString(),
  };
}

/**
 * Retrieve context specifically for safety/policy decisions.
 * Boosts standing orders and SOPs.
 */
export function retrieveSafetyContext(query: string): RAGContext {
  return retrieveContext(query, {
    boostCategories: ['standing_order', 'sop', 'policy', 'risk_register'],
    maxChunks: 3,
    minScore: 0.05,
  });
}

/**
 * Retrieve context for architecture/technical decisions.
 */
export function retrieveTechnicalContext(query: string): RAGContext {
  return retrieveContext(query, {
    boostCategories: ['architecture', 'product_spec', 'agent_guide'],
    maxChunks: 5,
    minScore: 0.05,
  });
}

/**
 * Quick check: does the RAG store have relevant info for this topic?
 * Returns true if at least one chunk scores above threshold.
 */
export function hasRelevantKnowledge(
  query: string,
  minScore: number = 0.15
): boolean {
  ingestBusinessDocuments();
  const results = vectorStore.search(query, { maxChunks: 1, minScore });
  return results.length > 0;
}

/**
 * Get RAG system status.
 */
export function getRAGStatus(): {
  initialized: boolean;
  stats: ReturnType<typeof vectorStore.getStats>;
} {
  const stats = vectorStore.getStats();
  return { initialized: stats.initialized, stats };
}
