import { Message, ChatConfig, ChatResponse } from '../../types/fusemind/messages';

class ChatService {
    private config: ChatConfig = {
        model: 'gpt-4',
        temperature: 0.7,
        maxTokens: 2000
    };

    private context: Message[] = [];

    async sendMessage(message: Message): Promise<ChatResponse> {
        try {
            // Add message to context
            this.context.push(message);

            // Prepare the messages for ChatGPT
            const messages = this.context.map(msg => ({
                role: msg.type === 'user' ? 'user' : 'assistant',
                content: msg.content
            }));

            // Make API call to ChatGPT
            const response = await fetch('/api/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    messages,
                    ...this.config
                })
            });

            if (!response.ok) {
                throw new Error('Failed to get response from ChatGPT');
            }

            const data = await response.json();

            // Create response message
            const responseMessage: Message = {
                id: Date.now().toString(),
                content: data.message,
                type: 'system',
                timestamp: new Date()
            };

            // Add response to context
            this.context.push(responseMessage);

            // Return formatted response
            return {
                message: responseMessage,
                usage: data.usage
            };
        } catch (error) {
            console.error('Error in ChatService:', error);
            throw error;
        }
    }

    setConfig(config: Partial<ChatConfig>) {
        this.config = { ...this.config, ...config };
    }

    clearContext() {
        this.context = [];
    }

    getContext(): Message[] {
        return [...this.context];
    }
}

export const chatService = new ChatService(); 