
import express from 'express';

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

const router = express.Router();

router.post('/', async (req, res) => {
    try {
        const { message, context } = req.body;
        const apiKey = process.env.GEMINI_API_KEY;

        if (!apiKey) {
            return res.status(500).json({ error: 'AI API Key not configured' });
        }

        const genAI = new GoogleGenerativeAI(apiKey);
        const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash-exp" });

        const systemInstruction = `
You are the "Golden Castel Pro AI Decision Engine".
Your goal is to answer questions about the business using ONLY the provided context.

RULES:
1.  **Scope**: You have access to the detailed financial snapshot provided below.
2.  **Privacy**: Do not reveal internal IDs (UUIDs) unless asked.
3.  **Tone**: Professional, executive summary style. Concise.
4.  **Unknowns**: If the data isn't in the provided context, say "I don't have that record."
5.  **Currency**: All monetary values are in AED.
6.  **Formatting**: Use bolding for important numbers (e.g., **AED 5,000**).

CONTEXT DATA:
${context || 'No data context provided.'}
    `;

        const chat = model.startChat({
            history: [
                {
                    role: "user",
                    parts: [{ text: systemInstruction }],
                },
                {
                    role: "model",
                    parts: [{ text: "Acknowledged. I have ingested the latest business data. I am ready to answer queries regarding customers, financials, and projects." }],
                },
            ],
        });

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

        res.json({ response });
    } catch (error: any) {
        console.error('AI Error:', error);
        res.status(500).json({ error: 'Failed to generate response', details: error.message });
    }
});

export default router;
