import type { Provider } from "./types.js";

const PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini", "hermes-agent"];

function normalizeBaseUrl(value: string) {
  const trimmed = value.trim();
  if (!trimmed) {
    throw new Error("SYBIL_TUI_API_BASE_URL cannot be empty");
  }

  let parsed: URL;
  try {
    parsed = new URL(trimmed);
  } catch {
    throw new Error(`Invalid SYBIL_TUI_API_BASE_URL: ${trimmed}`);
  }

  const normalizedPath = parsed.pathname.replace(/\/+$/, "");
  parsed.pathname = normalizedPath || "/";
  return parsed.toString().replace(/\/$/, "");
}

function parseProvider(value: string | undefined): Provider {
  const trimmed = value?.trim().toLowerCase();
  if (!trimmed) return "openai";
  if (PROVIDERS.includes(trimmed as Provider)) return trimmed as Provider;
  throw new Error(`Invalid SYBIL_TUI_DEFAULT_PROVIDER: ${value}`);
}

function parsePositiveInt(value: string | undefined, fallback: number) {
  if (!value?.trim()) return fallback;
  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed) || parsed <= 0) {
    throw new Error(`Invalid positive integer value: ${value}`);
  }
  return parsed;
}

const apiBaseUrlValue =
  process.env.SYBIL_TUI_API_BASE_URL?.trim() || process.env.SYBIL_API_BASE_URL?.trim() || "http://127.0.0.1:8787";

export const config = {
  apiBaseUrl: normalizeBaseUrl(apiBaseUrlValue),
  adminToken: process.env.SYBIL_TUI_ADMIN_TOKEN?.trim() || process.env.SYBIL_ADMIN_TOKEN?.trim() || null,
  defaultProvider: parseProvider(process.env.SYBIL_TUI_DEFAULT_PROVIDER),
  defaultModel: process.env.SYBIL_TUI_DEFAULT_MODEL?.trim() || null,
  searchNumResults: parsePositiveInt(process.env.SYBIL_TUI_SEARCH_NUM_RESULTS, 10),
};
