import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { useChatStore } from '../lib/store/chat-store';
import { LLMService } from '../services/llm-service';
import { ChatService } from '../services/chat-service';
import { DraftService } from '../lib/db/draft-service';
import { db } from '../lib/db';

describe('Fast Track Integration Tests', () => {
    beforeEach(async () => {
        await db.delete();
        await db.open();
        useChatStore.setState({
            messages: [],
            isLoading: false,
            isProcessing: false,
            isFastTrack: false,
            currentIntent: null
        });
        vi.restoreAllMocks();
    });

    afterEach(async () => {
        await db.delete();
    });

    it('should toggle Fast Track mode correctly', () => {
        const { toggleFastTrack } = useChatStore.getState();

        expect(useChatStore.getState().isFastTrack).toBe(false);

        toggleFastTrack();
        expect(useChatStore.getState().isFastTrack).toBe(true);

        toggleFastTrack();
        expect(useChatStore.getState().isFastTrack).toBe(false);
    });

    it('should bypass Teacher Agent logic when Fast Track is active', async () => {
        // Spy on LLM service to ensure it's NOT called
        const llmSpy = vi.spyOn(LLMService, 'getTeacherResponseStream');

        // Mock ChatService.generateGhostwriterDraftStream to simulate success callback
        const ghostwriterSpy = vi.spyOn(ChatService, 'generateGhostwriterDraftStream').mockImplementation(
            async (_history, _intent, _sid, callbacks) => {
                callbacks.onToken('# Test Draft');
                await callbacks.onComplete({
                    id: 123,
                    sessionId: 'test-session',
                    title: 'Test Draft',
                    content: '# Test Draft\n\nThis is a test.',
                    tags: ['test'],
                    createdAt: Date.now(),
                    status: 'draft'
                });
            }
        );

        // Enable Fast Track
        useChatStore.getState().toggleFastTrack();

        // Send message
        await useChatStore.getState().addMessage("Here is my direct insight", 'user');

        // Verify LLM service was NOT called
        expect(llmSpy).not.toHaveBeenCalled();

        // Verify Ghostwriter was called
        expect(ghostwriterSpy).toHaveBeenCalledWith(
            expect.any(Array),
            'insight',
            expect.any(String),
            expect.any(Object)
        );

        // Verify results
        const { messages, isProcessing, currentIntent, currentDraft } = useChatStore.getState();

        expect(isProcessing).toBe(false);
        expect(currentIntent).toBe('insight'); // Fast track assumes insight
        expect(currentDraft).not.toBeNull();
        expect(currentDraft?.id).toBe(123);

        expect(messages.length).toBeGreaterThanOrEqual(2);
        expect(messages[1].role).toBe('assistant');
        expect(messages[1].content).toContain("Draft ready!");
        expect(messages[1].intent).toBe('insight');

        // Restore mocks
        ghostwriterSpy.mockRestore();
    });

    it('should resume normal Teacher Agent flow when Fast Track is disabled', async () => {
        // Spy on LLM service to ensure it IS called
        const llmSpy = vi.spyOn(LLMService, 'getTeacherResponseStream').mockImplementation(
            async (_input, _history, callbacks) => {
                if (callbacks.onComplete) await callbacks.onComplete("Normal response");
            }
        );

        // Fast Track is disabled by default
        await useChatStore.getState().addMessage("Venting here", 'user');

        // Verify LLM service WAS called
        expect(llmSpy).toHaveBeenCalled();

        const { messages } = useChatStore.getState();
        expect(messages[1].content).toBe("Normal response");
    });
});
