const crypto = require('crypto');
const fs = require('fs/promises');
const path = require('path');

function stableStringify(value) {
  if (Array.isArray(value)) {
    return `[${value.map(stableStringify).join(',')}]`;
  }
  if (value && typeof value === 'object') {
    const keys = Object.keys(value).sort();
    return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
  }
  return JSON.stringify(value);
}

function sha256(input) {
  return crypto.createHash('sha256').update(input).digest('hex');
}

function hashObject(value) {
  return sha256(stableStringify(value));
}

function nowIso() {
  return new Date().toISOString();
}

function sanitizeFilePart(value) {
  return String(value).replace(/[^a-zA-Z0-9_.-]+/g, '_');
}

async function writeTextFile(dir, baseName, content, ext = 'txt') {
  await fs.mkdir(dir, { recursive: true });
  const file = path.join(dir, `${sanitizeFilePart(baseName)}.${ext}`);
  await fs.writeFile(file, content, 'utf8');
  return file;
}

module.exports = {
  stableStringify,
  hashObject,
  nowIso,
  writeTextFile,
  sanitizeFilePart
};
