'use server';

import { geminiModel, SYSTEM_INSTRUCTION } from '@/lib/gemini';
import { BottleMetadataSchema, AnalysisResponse } from '@/types/whisky';
import { createServerActionClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { createHash } from 'crypto';

export async function analyzeBottle(base64Image: string): Promise<AnalysisResponse> {
    const supabase = createServerActionClient({ cookies });

    if (!process.env.GEMINI_API_KEY) {
        return { success: false, error: 'GEMINI_API_KEY is not configured.' };
    }

    try {
        // Ensure user is authenticated for tracking/billing
        const { data: { session } } = await supabase.auth.getSession();
        if (!session) {
            return { success: false, error: 'Nicht autorisiert oder Session abgelaufen.' };
        }

        // 1. Generate Hash for Caching
        const base64Data = base64Image.split(',')[1] || base64Image;
        const imageHash = createHash('sha256').update(base64Data).digest('hex');
        console.log(`[AI Cache] Checking hash: ${imageHash}`);

        // 2. Check Cache
        const { data: cachedResult } = await supabase
            .from('vision_cache')
            .select('result')
            .eq('hash', imageHash)
            .maybeSingle();

        if (cachedResult) {
            console.log(`[AI Cache] Hit! hash: ${imageHash}`);
            return {
                success: true,
                data: cachedResult.result as any,
            };
        }

        console.log(`[AI Cache] Miss. Calling Gemini...`);

        // 3. AI Analysis
        const result = await geminiModel.generateContent([
            {
                inlineData: {
                    data: base64Data,
                    mimeType: 'image/jpeg',
                },
            },
            { text: SYSTEM_INSTRUCTION },
        ]);

        const responseText = result.response.text();
        let jsonData = JSON.parse(responseText);

        if (Array.isArray(jsonData)) {
            jsonData = jsonData[0];
        }

        if (!jsonData) {
            throw new Error('Keine Daten in der KI-Antwort gefunden.');
        }

        const validatedData = BottleMetadataSchema.parse(jsonData);

        // 4. Store in Cache
        const { error: storeError } = await supabase
            .from('vision_cache')
            .insert({ hash: imageHash, result: validatedData });

        if (storeError) {
            console.warn(`[AI Cache] Storage failed: ${storeError.message}`);
        } else {
            console.log(`[AI Cache] Stored new result for hash: ${imageHash}`);
        }

        return {
            success: true,
            data: validatedData,
        };
    } catch (error) {
        console.error('Gemini Analysis Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'An unknown error occurred during analysis.',
        };
    }
}
