function sanitizeToken(value) {
  return String(value || "")
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

function optionalToken(value) {
  const token = sanitizeToken(value);
  return token || null;
}

export function buildTestNamespace({ leaseId, runtimeId } = {}) {
  return optionalToken(leaseId) || optionalToken(runtimeId) || "standalone";
}

export function readTestkitContext(env = {}) {
  const runtimeId = optionalToken(env.TESTKIT_RUNTIME_ID);
  const leaseId = optionalToken(env.TESTKIT_LEASE_ID);

  return {
    active: env.TESTKIT_ACTIVE === "1",
    runtimeId,
    leaseId,
    namespace: buildTestNamespace({ leaseId, runtimeId }),
    rawEnv: env,
  };
}
