import { loadTextFile, saveTextFile } from "./file-service.js";
import {
  gcodeProgramPath,
  machineIniPath,
  normalizeOpfsPath,
  parameterFilePath,
  sessionSnapshotPath,
  toolTablePath,
} from "./path-model.js";

export const SESSION_SNAPSHOT_FORMAT = "linuxcnc-wasm-session-snapshot";
export const SESSION_SNAPSHOT_VERSION = 1;

function assertPlainObject(value, label) {
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${label} must be a plain object.`);
  }
}

function optionalOpfsPath(value, label) {
  if (value === undefined) {
    return undefined;
  }
  if (typeof value !== "string") {
    throw new Error(`${label} must be a string.`);
  }
  return normalizeOpfsPath(value);
}

function requiredSnapshotFilePath(files, key, label) {
  const value = files[key];
  if (typeof value !== "string") {
    throw new Error(`${label} must be a string.`);
  }
  return normalizeOpfsPath(value);
}

function validateMachineSessionSnapshotPayload(payload, machineId) {
  assertPlainObject(payload, "machine session snapshot payload");
  if (payload.machineId !== machineId) {
    throw new Error(`Machine session snapshot id mismatch: ${payload.machineId}`);
  }
  assertPlainObject(payload.files, "machine session snapshot files");
  requiredSnapshotFilePath(payload.files, "ini", "machine session INI OPFS path");
  requiredSnapshotFilePath(payload.files, "parameters", "machine session parameter OPFS path");
  requiredSnapshotFilePath(payload.files, "toolTable", "machine session tool table OPFS path");
  optionalOpfsPath(payload.files.gcode, "machine session G-code OPFS path");
  return payload;
}

export function createMachineSessionSnapshotPayload(machineId, options = {}) {
  assertPlainObject(options, "machine session snapshot options");
  const ini = optionalOpfsPath(options.iniOpfsPath, "INI OPFS path") ??
    machineIniPath(machineId, options.iniFilename);
  const parameters = optionalOpfsPath(options.parameterOpfsPath, "parameter OPFS path") ??
    parameterFilePath(machineId, options.parameterFilename);
  const toolTable = optionalOpfsPath(options.toolTableOpfsPath, "tool table OPFS path") ??
    toolTablePath(machineId, options.toolTableFilename);
  const gcode = optionalOpfsPath(options.gcodeOpfsPath, "G-code OPFS path") ??
    (options.gcodeFilename === undefined ? undefined : gcodeProgramPath(options.gcodeFilename));

  return {
    machineId,
    files: {
      ini,
      parameters,
      toolTable,
      ...(gcode === undefined ? {} : { gcode }),
    },
  };
}

export function createSessionSnapshot(sessionId, payload, options = {}) {
  sessionSnapshotPath(sessionId, options.filename);
  assertPlainObject(payload, "snapshot payload");
  if (options.metadata !== undefined) {
    assertPlainObject(options.metadata, "snapshot metadata");
  }

  return {
    format: SESSION_SNAPSHOT_FORMAT,
    version: SESSION_SNAPSHOT_VERSION,
    sessionId,
    createdAt: options.createdAt ?? new Date().toISOString(),
    metadata: options.metadata ?? {},
    payload,
  };
}

export function validateSessionSnapshot(snapshot, sessionId) {
  assertPlainObject(snapshot, "session snapshot");
  if (snapshot.format !== SESSION_SNAPSHOT_FORMAT) {
    throw new Error(`Unsupported session snapshot format: ${snapshot.format}`);
  }
  if (snapshot.version !== SESSION_SNAPSHOT_VERSION) {
    throw new Error(`Unsupported session snapshot version: ${snapshot.version}`);
  }
  if (snapshot.sessionId !== sessionId) {
    throw new Error(`Session snapshot id mismatch: ${snapshot.sessionId}`);
  }
  assertPlainObject(snapshot.metadata, "snapshot metadata");
  assertPlainObject(snapshot.payload, "snapshot payload");
  return snapshot;
}

export async function saveSessionSnapshot(sessionId, payload, options = {}) {
  const snapshot = createSessionSnapshot(sessionId, payload, options);
  const path = sessionSnapshotPath(sessionId, options.filename);
  await saveTextFile(path, `${JSON.stringify(snapshot, null, 2)}\n`, options.storage);
  return snapshot;
}

export async function saveMachineSessionSnapshot(sessionId, machineId, options = {}) {
  assertPlainObject(options, "machine session snapshot save options");
  const payload = createMachineSessionSnapshotPayload(machineId, options);
  return saveSessionSnapshot(sessionId, payload, options);
}

export async function loadMachineSessionSnapshot(sessionId, machineId, options = {}) {
  const snapshot = await loadSessionSnapshot(sessionId, options);
  validateMachineSessionSnapshotPayload(snapshot.payload, machineId);
  return snapshot;
}

export async function loadSessionSnapshot(sessionId, options = {}) {
  const path = sessionSnapshotPath(sessionId, options.filename);
  const text = await loadTextFile(path, options.storage);
  let snapshot;
  try {
    snapshot = JSON.parse(text);
  } catch (error) {
    throw new Error(`Invalid session snapshot JSON: ${error.message}`);
  }
  return validateSessionSnapshot(snapshot, sessionId);
}
