const PROVIDER_PREFIXES = {
  deepseek: "DEEPSEEK",
  glm: "GLM",
  gemini: "GEMINI",
  openai: "OPENAI",
};

const STAGE_DEFAULT_MODELS = {
  search_vision: "gemini-2.5-pro-preview-p",
  chatbot_intent: "deepseek-v4-flash",
};

const STAGE_ENV_PREFIXES = {
  search_vision: "SEARCH_VISION",
  chatbot_intent: "CHATBOT_INTENT",
};

function parseOptionalString(value) {
  if (typeof value !== "string") return undefined;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}

function normalizeProvider(value) {
  return parseOptionalString(value)?.toLowerCase();
}

export function resolveStageProviderFromEnv(stage, env = process.env) {
  const prefix = STAGE_ENV_PREFIXES[stage];
  if (!prefix) return undefined;
  return normalizeProvider(env[`${prefix}_LLM_PROVIDER`]);
}

export function resolveStageModelFromEnv(stage, env = process.env) {
  const prefix = STAGE_ENV_PREFIXES[stage];
  if (!prefix) {
    return parseOptionalString(env.LLM_MODEL);
  }

  if (stage === "search_vision") {
    return parseOptionalString(env.SEARCH_VISION_LLM_MODEL)
      ?? parseOptionalString(env.SEARCH_VISION_MODEL)
      ?? parseOptionalString(env.LLM_MODEL)
      ?? STAGE_DEFAULT_MODELS.search_vision;
  }

  return parseOptionalString(env[`${prefix}_LLM_MODEL`])
    ?? parseOptionalString(env.LLM_MODEL)
    ?? STAGE_DEFAULT_MODELS[stage];
}

export function resolveProviderCredentialFromEnv(provider, env = process.env) {
  const key = normalizeProvider(provider);
  const prefix = key ? PROVIDER_PREFIXES[key] ?? key.toUpperCase() : "";
  const baseUrl = prefix ? parseOptionalString(env[`${prefix}_LLM_BASE_URL`]) : undefined;
  const apiKey = prefix ? parseOptionalString(env[`${prefix}_LLM_API_KEY`]) : undefined;
  if (!baseUrl || !apiKey) {
    return null;
  }
  return {
    provider: key,
    baseUrl: baseUrl.replace(/\/+$/, ""),
    apiKey,
  };
}

export function resolveStageRuntimeFromEnv(stage, env = process.env) {
  const model = resolveStageModelFromEnv(stage, env);
  const provider = resolveStageProviderFromEnv(stage, env);
  const credential = provider ? resolveProviderCredentialFromEnv(provider, env) : null;
  if (credential) {
    return {
      ...credential,
      model,
    };
  }

  const legacyApiKey = parseOptionalString(env.LLM_API_KEY);
  const legacyBaseUrl = parseOptionalString(env.LLM_BASE_URL);
  if (legacyApiKey && legacyBaseUrl) {
    return {
      provider: normalizeProvider(env.LLM_PROVIDER) ?? "env",
      baseUrl: legacyBaseUrl.replace(/\/+$/, ""),
      apiKey: legacyApiKey,
      model,
    };
  }

  return null;
}
