export const SERVER_ORIGIN_STORAGE_KEY = "codexRemote.serverOrigin";

export function normalizeServerOrigin(value) {
  const input = String(value ?? "").trim();
  if (!input) throw new Error("invalid_server_address");
  let url;
  try {
    url = new URL(input.includes("://") ? input : `https://${input}`);
  } catch {
    throw new Error("invalid_server_address");
  }
  if (url.protocol !== "https:") throw new Error("secure_server_required");
  if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
    throw new Error("invalid_server_address");
  }
  return url.origin;
}

export function readSavedServerOrigin(storage = globalThis.localStorage) {
  try {
    const value = storage?.getItem(SERVER_ORIGIN_STORAGE_KEY);
    return value ? normalizeServerOrigin(value) : "";
  } catch {
    return "";
  }
}

export function writeSavedServerOrigin(storage = globalThis.localStorage, value) {
  const origin = normalizeServerOrigin(value);
  storage?.setItem(SERVER_ORIGIN_STORAGE_KEY, origin);
  return origin;
}

export function clearSavedServerOrigin(storage = globalThis.localStorage) {
  try { storage?.removeItem(SERVER_ORIGIN_STORAGE_KEY); } catch {}
}

export function getApiBase(explicitUrl, options = {}) {
  if (explicitUrl) return explicitUrl;
  if (!options.isNative) return "/api";
  const origin = readSavedServerOrigin(options.storage);
  return origin ? `${origin}/api` : "/api";
}
