'use server';

import { scanLabel } from '@/app/actions/scanner';
import { analyzeBottleOpenRouter } from './analyze-bottle-openrouter';
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(input: any): Promise<AnalysisResponse & { wb_id?: string }> {
    try {
        // Helper to get value from either FormData or POJO
        const getValue = (obj: any, key: string): string | null => {
            if (obj && typeof obj.get === 'function') return obj.get(key) as string | null;
            if (obj && typeof obj[key] !== 'undefined') return String(obj[key]);
            return null;
        };

        const provider = getValue(input, 'provider') || 'openrouter';
        const locale = getValue(input, 'locale') || 'de';

        console.log(`[magicScan] Start (Provider: ${provider}, Locale: ${locale})`);

        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`);

        // Prepare context for sub-services (handle if input is not FormData)
        let context = input;
        if (!(input instanceof FormData)) {
            console.log('[magicScan] Converting POJO to FormData for sub-services...');
            context = new FormData();
            // Copy keys if possible
            if (input && typeof input === 'object') {
                Object.keys(input).forEach(key => context.append(key, input[key]));
            }
        }

        // Add tags to context
        context.set('tags', JSON.stringify(tagNames));

        // 1. AI Analysis
        let aiResponse: any;
        if (provider === 'mistral' || provider === 'openrouter') {
            aiResponse = await analyzeBottleOpenRouter(context);
        } else {
            aiResponse = await scanLabel(context);
        }

        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)
        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,
                perf: aiResponse.perf,
                raw: aiResponse.raw
            };
        }

        // 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,
                    });

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

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

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

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