'use server';

import { analyzeBottle } from './analyze-bottle';
import { analyzeBottleMistral } from './analyze-bottle-mistral';
import { searchBraveForWhiskybase } from './brave-search';
import { getAllSystemTags } from './tags';
import { supabase } from '@/lib/supabase';
import { supabaseAdmin } from '@/lib/supabase-admin';
import { AnalysisResponse, BottleMetadata } from '@/types/whisky';

export async function magicScan(base64Image: string, provider: 'gemini' | 'mistral' = 'gemini', locale: string = 'de'): Promise<AnalysisResponse & { wb_id?: string }> {
    try {
        console.log('[magicScan] Starting scan process...');
        if (!supabase) {
            throw new Error('Supabase client is not initialized. Check environment variables.');
        }

        // 0. Fetch available tags for constrained generation
        const systemTags = await getAllSystemTags();
        const tagNames = systemTags.map(t => t.name);
        console.log(`[magicScan] Fetched ${tagNames.length} system tags`);

        // 1. AI Analysis
        let aiResponse: any;
        if (provider === 'mistral') {
            aiResponse = await analyzeBottleMistral(base64Image, tagNames, locale);
        } else {
            aiResponse = await analyzeBottle(base64Image, tagNames, locale);
        }

        if (!aiResponse.success || !aiResponse.data) {
            return aiResponse;
        }

        const data: BottleMetadata = aiResponse.data;
        const searchString = aiResponse.search_string || `${data.distillery || ''} ${data.name || ''} ${data.vintage || data.age || ''}`.trim();

        if (!searchString) {
            return { ...aiResponse, wb_id: undefined };
        }

        // 2. DB Cache Check (global_products)
        // We use the regular supabase client for reading
        const { data: cacheHit } = await supabase
            .from('global_products')
            .select('wb_id')
            .textSearch('search_vector', searchString, {
                config: 'simple',
                type: 'websearch'
            })
            .limit(1)
            .maybeSingle();

        if (cacheHit) {
            console.log(`[Magic Scan] Cache Hit for ${searchString}: ${cacheHit.wb_id}`);
            return {
                ...aiResponse,
                wb_id: cacheHit.wb_id
            };
        }

        // 3. Fallback to Brave Search
        console.log(`[Magic Scan] Cache Miss for ${searchString}. Calling Brave...`);
        const braveResult = await searchBraveForWhiskybase(searchString);

        if (braveResult.success && braveResult.id) {
            console.log(`[Magic Scan] Brave found ID: ${braveResult.id}`);

            // 4. Cache Write (using Admin client)
            if (supabaseAdmin) {
                const { error: saveError } = await supabaseAdmin
                    .from('global_products')
                    .insert({
                        wb_id: braveResult.id,
                        full_name: searchString, // We save the search string as the name for future hits
                    });

                if (saveError) {
                    console.warn(`[Magic Scan] Failed to save to global_products: ${saveError.message}`);
                }
            }

            return {
                ...aiResponse,
                wb_id: braveResult.id
            };
        }

        return {
            ...aiResponse,
            wb_id: undefined
        };

    } catch (error) {
        console.error('Magic Scan Error:', error);
        return {
            success: false,
            error: error instanceof Error ? error.message : 'Magic Scan failed.'
        };
    }
}
