import { loadTextFile, saveTextFile } from "./file-service.js";
import { sessionSnapshotPath } 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.`);
  }
}

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 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);
}
