import { GoogleGenerativeAI } from '@google/generative-ai';

const API_KEY = process.env.GEMINI_API_KEY || process.env.API_KEY;
const MODEL_ID = 'gemini-flash-lite-latest';

// Store chat sessions in memory
const chatSessions = new Map<string, any>();

export class AIService {
    static async chat(userId: string, systemInstruction: string, userMessage: string, sessionId: string) {
        if (!API_KEY) {
            throw new Error('AI service not configured');
        }

        const chatKey = `${userId}-${sessionId || 'default'}`;

        // Get or create chat session
        let chat = chatSessions.get(chatKey);

        if (!chat || systemInstruction) {
            const ai = new GoogleGenerativeAI(API_KEY);
            // Create new chat with system instruction
            const model = ai.getGenerativeModel({
                model: MODEL_ID,
                systemInstruction: systemInstruction || 'You are a helpful fitness coach.'
            });

            chat = model.startChat({
                history: []
            });

            chatSessions.set(chatKey, chat);
        }

        const result = await chat.sendMessage(userMessage);
        const response = result.response.text();

        return { response };
    }

    static async clearChat(userId: string, sessionId: string) {
        const chatKey = `${userId}-${sessionId}`;
        chatSessions.delete(chatKey);
    }
}
