const { onRequest } = require("firebase-functions/v2/https");
const { GoogleGenerativeAI } = require("@google/generative-ai");
const admin = require("firebase-admin");

admin.initializeApp();

// NOTE: Ideally, set this key via Firebase secrets:
// firebase functions:secrets:set GEMINI_API_KEY
// and access it via process.env.GEMINI_API_KEY
// For now, using the key from user code for immediate functionality.
const GEMINI_API_KEY = "AIzaSyCcYMqNJLmtcDnNd1FvgY45LDiE3IPNsyM";
const genAI = new GoogleGenerativeAI(GEMINI_API_KEY);

exports.generateAyuelSuggestion = onRequest({ cors: true }, async (request, response) => {
    console.log("🔵 Cloud Function called");
    console.log("🔵 Request body:", JSON.stringify(request.body));

    // 1. Extract parameters from the request body
    const {
        transcript,
        persona,
        energyBaseline,
        decisionStyle,
        focusAreas,
        boundariesJson,
        gentleNudges,
        focusProtection,
        energyLevel
    } = request.body;

    if (!transcript) {
        console.error("🔴 Missing transcript in request");
        response.status(400).json({ error: "Missing 'transcript' in request data." });
        return;
    }

    console.log("🔵 Transcript:", transcript);

    // 2. Build the System Prompt (similar to gemini_service.dart)
    // Safe defaults in case optional fields are missing
    const userPersona = persona || "Unknown";
    const userEnergyBaseline = energyBaseline || "Unknown";
    const currentEnergy = energyLevel || "Unknown";

    const focusAreasStr = focusAreas || "";

    const boundariesStr = boundariesJson || "";

    const currentTime = new Date().toString();

    const prompt = `
You are "Ayuel", a calm personal assistant.You do not judge.You help users make everyday decisions with minimal pressure. 
keep responses short(1 - 2 sentences). 
Respect user boundaries.
Output ONLY valid JSON matching this schema:
{
    "category": "Food|Time|SelfCare|Home|Movement|Spending|Tech",
        "title": "Short Title",
            "suggestion": "1-2 sentences max",
                "why": "1 sentence max explanation",
                    "actions": [
                        { "label": "Action 1", "type": "confirm|defer|regenerate|timer" }
                    ]
}

Context:
User Persona: ${userPersona}
Energy Baseline: ${userEnergyBaseline}
Current Energy: ${currentEnergy}
Focus Areas: ${focusAreasStr}
Boundaries: ${boundariesStr}
Gentle Nudges: ${gentleNudges}
Current Time: ${currentTime}

User Transcript: "${transcript}"
    `;

    // 3. Call Gemini using direct HTTP request (bypassing SDK to use v1 API)
    console.log("🔵 Calling Gemini API directly...");
    console.log("🔵 Using model: gemini-2.0-flash via v1 API");

    try {
        const apiUrl = `https://generativelanguage.googleapis.com/v1/models/gemini-2.0-flash:generateContent?key=${GEMINI_API_KEY}`;

        const requestBody = {
            contents: [{
                parts: [{
                    text: prompt
                }]
            }]
        };

        console.log("🔵 Sending request to Gemini API...");
        const apiResponse = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestBody)
        });

        if (!apiResponse.ok) {
            const errorText = await apiResponse.text();
            console.error("🔴 Gemini API HTTP error:", apiResponse.status, errorText);
            throw new Error(`Gemini API error: ${apiResponse.status} - ${errorText}`);
        }

        const apiData = await apiResponse.json();
        console.log("🔵 Gemini API response:", JSON.stringify(apiData));

        if (!apiData.candidates || !apiData.candidates[0] || !apiData.candidates[0].content) {
            console.error("🔴 Unexpected API response format");
            throw new Error("Unexpected API response format");
        }

        const text = apiData.candidates[0].content.parts[0].text;
        console.log("🔵 Text extracted:", text);

        // 4. Clean and parse JSON
        let cleanText = text;
        // Strip markdown code blocks if present
        if (text.includes("```json")) {
            cleanText = text.split("```json")[1].split("```")[0];
        } else if (text.includes("```")) {
            cleanText = text.split("```")[1].split("```")[0];
        }

        console.log("🔵 Clean text to parse:", cleanText);
        try {
            const jsonMap = JSON.parse(cleanText);
            console.log("🔵 Successfully parsed JSON:", jsonMap);
            response.json(jsonMap);
        } catch (parseError) {
            console.error("🔴 JSON Parse Error:", parseError, "Raw text:", text);
            // Return a safe fallback if parsing failed but we got some text
            response.json({
                category: "General",
                title: "Processing Error",
                suggestion: "I heard you, but I had trouble structuring my thought. Please try again.",
                why: "Internal format error.",
                actions: [{ label: "Try again", type: "regenerate" }]
            });
        }

    } catch (e) {
        console.error("🔴 Gemini API Error:", e);
        // Fallback response matching AyuelResponse model
        response.json({
            category: "General",
            title: "I'm listening",
            suggestion: "I couldn't quite process that. Could you try asking again?",
            why: "My connection seems a bit weak right now.",
            actions: [{ label: "Try again", type: "regenerate" }]
        });
    }
});
