import { loadTextFile, saveTextFile } from "./file-service.js";
import { toolTablePath } from "./path-model.js";

const DEFAULT_WASM_TOOL_TABLE_PATH = "/work/tool.tbl";

function requireToolTableSdk(interp) {
  for (const method of ["writeTextFile", "readTextFile", "loadToolTable", "saveToolTable"]) {
    if (typeof interp?.[method] !== "function") {
      throw new Error(`interpreter SDK is missing ${method}().`);
    }
  }
}

function resolvePaths(machineId, options = {}) {
  const opfsPath = options.opfsPath ?? toolTablePath(machineId, options.filename);
  const wasmPath = options.wasmPath ?? DEFAULT_WASM_TOOL_TABLE_PATH;
  return { opfsPath, wasmPath };
}

export async function loadMachineToolTableFromOpfs(interp, machineId, options = {}) {
  requireToolTableSdk(interp);
  const { opfsPath, wasmPath } = resolvePaths(machineId, options);
  const text = await loadTextFile(opfsPath, options.storage);
  interp.writeTextFile(wasmPath, text);
  return {
    opfsPath,
    wasmPath,
    result: interp.loadToolTable(wasmPath, {
      randomToolChanger: options.randomToolChanger === true,
    }),
  };
}

export async function saveMachineToolTableToOpfs(interp, machineId, options = {}) {
  requireToolTableSdk(interp);
  const { opfsPath, wasmPath } = resolvePaths(machineId, options);
  const result = interp.saveToolTable(wasmPath);
  const savedText = interp.readTextFile(wasmPath);

  await saveTextFile(opfsPath, savedText, options.storage);

  return {
    opfsPath,
    wasmPath,
    result,
    savedText,
  };
}
