import { AI_KNOWLEDGE_EMBEDDING_DIMENSIONS } from "@/modules/core/server/schema";

export type AiRuntimeConfig = {
  baseUrl: string;
  apiKey: string;
  chatModel: string;
  embeddingModel: string;
  embeddingDimensions: number;
};

export type AiRuntimeConfigResult =
  | { success: true; config: AiRuntimeConfig }
  | { success: false; reason: string };

const DEFAULT_CHAT_MODEL = "gpt-4.1-mini";
const DEFAULT_EMBEDDING_MODEL = "text-embedding-3-small";

function readOptionalEnv(name: string): string {
  return process.env[name]?.trim() ?? "";
}

export function getAiRuntimeConfig(): AiRuntimeConfigResult {
  const apiKey = readOptionalEnv("AI_API_KEY");
  if (!apiKey) {
    return { success: false, reason: "AI_API_KEY 未配置" };
  }

  return {
    success: true,
    config: {
      baseUrl: readOptionalEnv("AI_BASE_URL"),
      apiKey,
      chatModel: readOptionalEnv("AI_CHAT_MODEL") || DEFAULT_CHAT_MODEL,
      embeddingModel: readOptionalEnv("AI_EMBEDDING_MODEL") || DEFAULT_EMBEDDING_MODEL,
      embeddingDimensions: AI_KNOWLEDGE_EMBEDDING_DIMENSIONS,
    },
  };
}
