import { assertAIConfigured } from "@/lib/ai/config";
import { openaiProvider } from "@/lib/ai/providers/openai";
import { anthropicProvider } from "@/lib/ai/providers/anthropic";
import { getRagChatConfig } from "./config";
import {
  buildRagChatSystemPrompt,
  buildRagChatUserPrompt,
  formatKnowledgeForPrompt,
} from "./prompt";
import { retrieveKnowledge } from "./retrieve";
import type { KnowledgePlatform, KnowledgeTopic, RagCitation } from "./types";
import { hitsToCitations } from "./retrieve";

export interface RagQueryInput {
  platform: KnowledgePlatform;
  question: string;
  projectContext?: string;
  topicBoost?: KnowledgeTopic | KnowledgeTopic[];
  topK?: number;
}

export interface RagQueryResult {
  answer: string;
  provider: string;
  model: string;
  citations: RagCitation[];
  platform: KnowledgePlatform;
}

export async function answerRagQuery(input: RagQueryInput): Promise<RagQueryResult> {
  const hits = await retrieveKnowledge({
    platform: input.platform,
    query: input.question,
    topK: input.topK,
    topicBoost: input.topicBoost ?? "customer_audience",
  });

  const knowledgeBlock = formatKnowledgeForPrompt(hits, input.platform, "chat");
  const config = getRagChatConfig();
  assertAIConfigured(config);

  const provider =
    config.provider === "openai" ? openaiProvider : anthropicProvider;

  const result = await provider.generateText({
    systemPrompt: buildRagChatSystemPrompt(input.platform),
    userPrompt: buildRagChatUserPrompt({
      question: input.question,
      knowledgeBlock,
      projectContext: input.projectContext,
    }),
  });

  return {
    answer: result.content.trim(),
    provider: result.provider,
    model: result.model,
    citations: hitsToCitations(hits, input.platform),
    platform: input.platform,
  };
}
