import test from 'node:test';
import assert from 'node:assert/strict';
import os from 'os';
import path from 'path';

import { hiddenHookTracker } from './HiddenHookTracker.js';
import { saveState } from './SaveState.js';

async function isolateSaveState(testId) {
  await saveState._writeQueue.catch(() => {});
  process.env.SAVE_DIR = path.join(os.tmpdir(), `sc-test-${testId}-${Date.now()}`);
  saveState._savePath = null;
  saveState._state = null;
  saveState._writeQueue = Promise.resolve();
}

test('initialize restores discovered hooks', async () => {
  await isolateSaveState('hooks-restore');
  hiddenHookTracker.initialize({ hidden_hooks_discovered: ['hook_a', 'hook_b'] });

  assert.equal(hiddenHookTracker.isDiscovered('hook_a'), true);
  assert.equal(hiddenHookTracker.isDiscovered('hook_c'), false);
});

test('initialize with no saved hooks starts empty', async () => {
  await isolateSaveState('hooks-empty');
  hiddenHookTracker.initialize({});

  assert.deepEqual(hiddenHookTracker.getDiscovered(), []);
});

test('discover adds a new hook', async () => {
  await isolateSaveState('hooks-discover');
  hiddenHookTracker.initialize({});

  hiddenHookTracker.discover('hook_x');

  assert.equal(hiddenHookTracker.isDiscovered('hook_x'), true);
});

test('discover is idempotent', async () => {
  await isolateSaveState('hooks-idempotent');
  hiddenHookTracker.initialize({});

  hiddenHookTracker.discover('hook_y');
  hiddenHookTracker.discover('hook_y');

  assert.equal(hiddenHookTracker.getDiscovered().length, 1);
});

test('getDiscovered returns sorted array', async () => {
  await isolateSaveState('hooks-sorted');
  hiddenHookTracker.initialize({ hidden_hooks_discovered: ['zz', 'aa', 'mm'] });

  assert.deepEqual(hiddenHookTracker.getDiscovered(), ['aa', 'mm', 'zz']);
});
