import { OpenAI } from "openai";
import Anthropic from "@anthropic-ai/sdk";
import { GoogleGenerativeAI } from "@google/generative-ai";
import { getSettings } from "./SettingsHelper"; // your DB helper

type ModelHandler = (prompt: string, inputText: string) => Promise<string>;

export async function aiModelsRepository(
  model: string,
  modelMode: string
): Promise<ModelHandler> {
  const settings = await getSettings();
  const apiKeys = settings.api_keys || {};

  // --- ChatGPT ---
  if (model === "chatgpt") {
    const openai = new OpenAI({
      apiKey: apiKeys.OPENAI_API_KEY, // from DB
    });

    return async (prompt: string, inputText: string) => {
      const completion = await openai.chat.completions.create({
        model: modelMode,
        messages: [
          { role: "system", content: prompt }, // instruction
          { role: "user", content: inputText }, // user text
        ],
        // temperature: 0.7,
      });

      return completion.choices[0].message.content || "";
    };
  }

  // --- Claude ---
  if (model === "claude") {
    const anthropic = new Anthropic({
      apiKey: apiKeys.CLAUDE_API_KEY, // from DB
    });

    return async (prompt: string, inputText: string) => {
      const completion = await anthropic.messages.create({
        model: modelMode,
        max_tokens: 1024,
        messages: [{ role: "user", content: `${prompt}\n\n${inputText}` }],
      });

      const textContent = completion.content
        .filter((block) => block.type === "text")
        .map((block) => (block as { type: "text"; text: string }).text)
        .join("\n");

      return textContent;
    };
  }

  // --- Gemini ---
  if (model === "gemini") {
    const geminiApiKey = process.env.GEMINI_API_KEY;
    if (!geminiApiKey) {
      throw new Error("GEMINI_API_KEY is not defined in environment variables.");
    }
    const genAI = new GoogleGenerativeAI(geminiApiKey);
    const modelInstance = genAI.getGenerativeModel({ model: modelMode });

    return async (prompt: string, inputText: string) => {
      const result = await modelInstance.generateContent({
        contents: [
          {
            role: "user",
            parts: [
              { text: prompt }, // instruction
              { text: inputText }, // user content
            ],
          },
        ],
      });

      const response = await result.response;
      return response.text();
    };
  }

  throw new Error(`Unsupported model or mode: ${model}:${modelMode}`);
}
