import { afterEach, describe, expect, it, vi } from 'vitest';
import { IdlePollLoop } from './idle-poll-loop.js';
afterEach(() => {
    vi.useRealTimers();
});
describe('IdlePollLoop', () => {
    it('dispatches poll commands after the startup-safe delay when the session is waiting for input', async () => {
        vi.useFakeTimers();
        const dispatchPollingPrompt = vi.fn();
        const loop = new IdlePollLoop({
            getStatus: () => 'waiting_input',
            getCommand: () => 'poll_message',
            isPollingCommand: (command) => command.includes('poll_message'),
            dispatchPollingPrompt,
            dispatchRegularIdleCommand: vi.fn(),
        });
        loop.start();
        await vi.advanceTimersByTimeAsync(1499);
        expect(dispatchPollingPrompt).not.toHaveBeenCalled();
        await vi.advanceTimersByTimeAsync(1);
        expect(dispatchPollingPrompt).toHaveBeenCalledTimes(1);
        expect(dispatchPollingPrompt).toHaveBeenCalledWith('poll_message');
    });
    it('does not dispatch when the session is busy', () => {
        const dispatchPollingPrompt = vi.fn();
        const loop = new IdlePollLoop({
            getStatus: () => 'thinking',
            getCommand: () => 'poll_message',
            isPollingCommand: (command) => command.includes('poll_message'),
            dispatchPollingPrompt,
            dispatchRegularIdleCommand: vi.fn(),
        });
        loop.start();
        expect(dispatchPollingPrompt).not.toHaveBeenCalled();
    });
    it('keeps only one delayed regular idle command scheduled', async () => {
        vi.useFakeTimers();
        const dispatchRegularIdleCommand = vi.fn();
        const loop = new IdlePollLoop({
            getStatus: () => 'waiting_input',
            getCommand: () => 'continue',
            isPollingCommand: () => false,
            dispatchPollingPrompt: vi.fn(),
            dispatchRegularIdleCommand,
            regularIdleDelayMs: 1500,
        });
        loop.start();
        loop.start();
        await vi.advanceTimersByTimeAsync(1499);
        expect(dispatchRegularIdleCommand).not.toHaveBeenCalled();
        await vi.advanceTimersByTimeAsync(1);
        expect(dispatchRegularIdleCommand).toHaveBeenCalledTimes(1);
        expect(dispatchRegularIdleCommand).toHaveBeenCalledWith('continue');
    });
    it('can cancel a scheduled regular idle command', async () => {
        vi.useFakeTimers();
        const dispatchRegularIdleCommand = vi.fn();
        const loop = new IdlePollLoop({
            getStatus: () => 'waiting_input',
            getCommand: () => 'continue',
            isPollingCommand: () => false,
            dispatchPollingPrompt: vi.fn(),
            dispatchRegularIdleCommand,
            regularIdleDelayMs: 1500,
        });
        loop.start();
        loop.stop();
        await vi.advanceTimersByTimeAsync(1500);
        expect(dispatchRegularIdleCommand).not.toHaveBeenCalled();
    });
});
