'use server';

import { getOpenRouterClient, OPENROUTER_VISION_MODEL, OPENROUTER_PROVIDER_PREFERENCES } from '@/lib/openrouter';
import { getFlavorRadarPrompt } from '@/lib/ai-prompts';
import { createClient } from '@/lib/supabase/server';
import { trackApiUsage } from './track-api-usage';

export async function extractFlavorProfile(nose: string, palate: string, finish: string, tagNames: string[]) {
    if (!process.env.OPENROUTER_API_KEY) {
        console.warn('OPENROUTER_API_KEY is not configured. Skipping flavor extraction.');
        return null;
    }

    // Don't waste API calls if notes are empty
    if (!nose && !palate && !finish && tagNames.length === 0) {
        return {
            smoky: 0,
            fruity: 0,
            spicy: 0,
            sweet: 0,
            floral: 0
        };
    }

    try {
        const supabase = await createClient();
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) return null;

        const client = getOpenRouterClient();
        const prompt = getFlavorRadarPrompt(nose, palate, finish, tagNames);

        const chatResponse = await client.chat.completions.create({
            model: OPENROUTER_VISION_MODEL,
            messages: [{ role: 'user', content: prompt }],
            response_format: { type: 'json_object' },
            temperature: 0.1,
            extra_body: {
                provider: OPENROUTER_PROVIDER_PREFERENCES
            }
        } as any);

        const rawContent = chatResponse.choices?.[0].message.content;
        if (!rawContent) throw new Error("Keine Antwort von OpenRouter");

        let jsonData;
        try {
            jsonData = JSON.parse(rawContent as string);
        } catch (e) {
            const cleanedText = (rawContent as string).replace(/```json/g, '').replace(/```/g, '');
            jsonData = JSON.parse(cleanedText);
        }

        await trackApiUsage({
            userId: user.id,
            apiType: 'gemini_ai', // Using this category for all LLM calls
            endpoint: 'openrouter/flavor-radar',
            success: true,
            provider: 'openrouter',
            model: OPENROUTER_VISION_MODEL,
            responseText: rawContent as string
        });

        return {
            smoky: Number(jsonData.smoky) || 0,
            fruity: Number(jsonData.fruity) || 0,
            spicy: Number(jsonData.spicy) || 0,
            sweet: Number(jsonData.sweet) || 0,
            floral: Number(jsonData.floral) || 0
        };

    } catch (error) {
        console.error('Error extracting flavor profile:', error);
        return null;
    }
}
