let activeSetup = null;
let activeRuntimeContext = null;

export function registerRepoSetup(setup) {
  activeSetup = setup || null;
}

export function getRepoSetup() {
  return activeSetup;
}

export function clearRepoSetup() {
  activeSetup = null;
}

export function registerRuntimeContext(context) {
  activeRuntimeContext = context || null;
}

export function getRuntimeContext() {
  return activeRuntimeContext;
}

export function clearRuntimeContext() {
  activeRuntimeContext = null;
}

export function getRuntimeHttp() {
  const context = getRuntimeContext();
  if (!context?.http) {
    throw new Error("Testkit runtime HTTP client is not available in this context");
  }
  return context.http;
}

export function getRuntimeEnv() {
  const context = getRuntimeContext();
  if (!context?.env) {
    throw new Error("Testkit runtime env is not available in this context");
  }
  return context.env;
}

export function runtimeJson(response) {
  return JSON.parse(response.body);
}

export function resolveHttpProfile(name) {
  if (!name) return null;

  const setup = getRepoSetup();
  if (!setup) return null;
  const profile = setup?.profiles?.http?.[name];
  if (!profile) {
    throw new Error(`Unknown testkit HTTP profile "${name}"`);
  }
  return profile;
}

export const runtimeHttp = {
  del(url, body, params) {
    return getRuntimeHttp().del(url, body, params);
  },
  file(data, filename, contentType) {
    return getRuntimeHttp().file(data, filename, contentType);
  },
  get(url, params) {
    return getRuntimeHttp().get(url, params);
  },
  patch(url, body, params) {
    return getRuntimeHttp().patch(url, body, params);
  },
  post(url, body, params) {
    return getRuntimeHttp().post(url, body, params);
  },
  put(url, body, params) {
    return getRuntimeHttp().put(url, body, params);
  },
};
