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

import { narrativePhaseTracker } from './NarrativePhaseTracker.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 saved phase', async () => {
  await isolateSaveState('phase-restore');
  narrativePhaseTracker.initialize({ narrative_phase: 'suspicion' });

  assert.equal(narrativePhaseTracker.getPhase(), 'suspicion');
});

test('initialize rejects unknown phase', async () => {
  await isolateSaveState('phase-unknown');
  narrativePhaseTracker.initialize({ narrative_phase: 'not_a_phase' });

  assert.equal(narrativePhaseTracker.getPhase(), 'normal_work');
});

test('initialize with no key defaults to normal_work', async () => {
  await isolateSaveState('phase-default');
  narrativePhaseTracker.initialize({});

  assert.equal(narrativePhaseTracker.getPhase(), 'normal_work');
});

test('forcePhase sets a valid phase', async () => {
  await isolateSaveState('phase-force-valid');
  narrativePhaseTracker.initialize({ narrative_phase: 'normal_work' });

  narrativePhaseTracker.forcePhase('investigation');

  assert.equal(narrativePhaseTracker.getPhase(), 'investigation');
});

test('forcePhase ignores an invalid phase', async () => {
  await isolateSaveState('phase-force-invalid');
  narrativePhaseTracker.initialize({ narrative_phase: 'unease' });

  narrativePhaseTracker.forcePhase('not_valid');

  assert.equal(narrativePhaseTracker.getPhase(), 'unease');
});

test('advance with unknown quest is a no-op', async () => {
  await isolateSaveState('phase-advance-unknown');
  narrativePhaseTracker.initialize({ narrative_phase: 'unease' });

  // ContentLoader.quests is empty in this test context because load() is never called.
  narrativePhaseTracker.advance('nonexistent-quest-id');

  assert.equal(narrativePhaseTracker.getPhase(), 'unease');
});
