'use server'; /** * Service to discover a Whiskybase ID for a given bottle. * Uses Google Custom Search JSON API to search Google and extracts the ID from the first result. */ export async function discoverWhiskybaseId(bottle: { name: string; distillery?: string; abv?: number; age?: number; distilled_at?: string; bottled_at?: string; batch_info?: string; }) { // Both Gemini and Custom Search often use the same API key if created via AI Studio const apiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY; const cx = '37e905eb03fd14e0f'; // Provided by user if (!apiKey) { return { success: false, error: 'GEMINI_API_KEY oder GOOGLE_API_KEY ist nicht konfiguriert.' }; } try { // Construct targeted search query const queryParts = [ bottle.distillery ? `${bottle.distillery}` : '', // Removed quotes for more fuzzy matching bottle.name ? `${bottle.name}` : '', bottle.abv ? `${bottle.abv}%` : '', bottle.age ? `${bottle.age} year old` : '', bottle.batch_info ? `"${bottle.batch_info}"` : '', bottle.distilled_at ? `distilled ${bottle.distilled_at}` : '', bottle.bottled_at ? `bottled ${bottle.bottled_at}` : '' ].filter(Boolean); const q = queryParts.join(' '); console.log('Whiskybase Search Query:', q); const url = `https://www.googleapis.com/customsearch/v1?key=${apiKey}&cx=${cx}&q=${encodeURIComponent(q)}`; const response = await fetch(url); const data = await response.json(); if (data.error) { console.error('Google API Error Response:', data.error); throw new Error(data.error.message || 'Google API Error'); } if (!data.items || data.items.length === 0) { return { success: false, error: `Keine Treffer auf Whiskybase gefunden. (Query: ${q})` }; } // Try to find the first result that looks like a valid product page // Pattern matches: https://www.whiskybase.com/whiskies/whisky/12345/name const wbRegex = /\/whisky\/(\d+)\//; for (const item of data.items) { const link = item.link; const match = link.match(wbRegex); if (match && match[1]) { return { success: true, id: match[1], url: link, title: item.title }; } } return { success: false, error: 'Konnte keine gültige Whiskybase-ID im Suchergebnis finden.' }; } catch (error) { console.error('Whiskybase Discovery Error:', error); return { success: false, error: error instanceof Error ? error.message : 'Fehler bei der Suche auf Whiskybase.' }; } }