export const LAB3_DEFAULT_TERMINAL_PATH = "/wetty";
export const LAB3_DEFAULT_USERNAME = "student";
export const LAB3_DEFAULT_WORKING_DIRECTORY = "/home/student/lab3";
export const LAB3_RUNTIME_CONFIG_PATH = "/courseware-runtime.json";

export type Lab3RuntimeConfig = {
  lab3TerminalUrl?: string;
  lab3Username?: string;
  lab3WorkingDirectory?: string;
};

export type ResolvedLab3RuntimeConfig = {
  terminalPath: string;
  username: string;
  workingDirectory: string;
};

export function getLab3TerminalPath(envValue?: string) {
  const trimmedValue = envValue?.trim();

  if (!trimmedValue) {
    return LAB3_DEFAULT_TERMINAL_PATH;
  }

  if (/^https?:\/\//i.test(trimmedValue)) {
    return trimmedValue;
  }

  return trimmedValue.startsWith("/") ? trimmedValue : `/${trimmedValue}`;
}

export function normalizeLab3RuntimeConfig(
  config?: Lab3RuntimeConfig,
): ResolvedLab3RuntimeConfig {
  return {
    terminalPath: getLab3TerminalPath(config?.lab3TerminalUrl),
    username: config?.lab3Username?.trim() || LAB3_DEFAULT_USERNAME,
    workingDirectory:
      config?.lab3WorkingDirectory?.trim() || LAB3_DEFAULT_WORKING_DIRECTORY,
  };
}

export async function fetchLab3RuntimeConfig() {
  const response = await fetch(LAB3_RUNTIME_CONFIG_PATH, { cache: "no-store" });

  if (!response.ok) {
    throw new Error(`Runtime config request failed: ${response.status}`);
  }

  const config = (await response.json()) as Lab3RuntimeConfig;
  return normalizeLab3RuntimeConfig(config);
}
