const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const {
  renameWithRetrySync,
  writeUtf8AtomicSync
} = require('../services/atomicFileReplace');

let renameAttempts = 0;
const delays = [];
const simulated = renameWithRetrySync('source', 'target', {
  attempts: 5,
  delayMs: 2,
  renameSync() {
    renameAttempts += 1;
    if (renameAttempts < 3) {
      const error = new Error('simulated Windows scanner lock');
      error.code = 'EPERM';
      throw error;
    }
  },
  sleepSync(delayMs) { delays.push(delayMs); }
});
assert.strictEqual(simulated.attempts, 3);
assert.deepStrictEqual(delays, [2, 4]);

let nonRetryAttempts = 0;
assert.throws(() => renameWithRetrySync('source', 'target', {
  renameSync() {
    nonRetryAttempts += 1;
    const error = new Error('not retryable');
    error.code = 'ENOENT';
    throw error;
  },
  sleepSync() { throw new Error('should not sleep'); }
}), /not retryable/);
assert.strictEqual(nonRetryAttempts, 1);

const root = fs.mkdtempSync(path.join(os.tmpdir(), 'plai-atomic-file-'));
try {
  const target = path.join(root, 'state.json');
  writeUtf8AtomicSync(target, '{"generation":1}\n');
  writeUtf8AtomicSync(target, '{"generation":2}\n');
  assert.deepStrictEqual(JSON.parse(fs.readFileSync(target, 'utf8')), { generation: 2 });
  assert.deepStrictEqual(fs.readdirSync(root), ['state.json']);
} finally {
  fs.rmSync(root, { recursive: true, force: true });
}

process.stdout.write(`${JSON.stringify({
  ok: true,
  retryableWindowsEpermRecovered: true,
  boundedAttempts: simulated.attempts,
  nonRetryableErrorFailedImmediately: true,
  uniqueTemporaryFileCleaned: true,
  atomicReplacementVerified: true,
  productionFilesTouched: false,
  productionProcessRestarted: false
}, null, 2)}\n`);
