// Open Food Facts API Helper
// Free API for food product information lookup

export interface ProductData {
  barcode: string;
  name: string;
  brand?: string;
  category?: string;
  description?: string;
  imageUrl?: string;
}

// Category mapping from Open Food Facts to our categories
const CATEGORY_MAPPING: Record<string, string> = {
  // Produce
  'fruits': 'Produce',
  'vegetables': 'Produce',
  'vegetable': 'Produce',
  'fruit': 'Produce',
  'produce': 'Produce',
  'fresh': 'Produce',
  'corn': 'Produce',
  'tomato': 'Produce',
  'potato': 'Produce',
  'onion': 'Produce',
  'carrot': 'Produce',
  'apple': 'Produce',
  'banana': 'Produce',
  'orange': 'Produce',
  
  // Canned Goods
  'canned': 'Canned Goods',
  'tinned': 'Canned Goods',
  'conserve': 'Canned Goods',
  'preserved': 'Canned Goods',
  'jar': 'Canned Goods',
  
  // Bakery
  'bread': 'Bakery',
  'bakery': 'Bakery',
  'baked': 'Bakery',
  'bun': 'Bakery',
  'roll': 'Bakery',
  'bagel': 'Bakery',
  'muffin': 'Bakery',
  'pastry': 'Bakery',
  
  // Grains
  'pasta': 'Grains',
  'rice': 'Grains',
  'grain': 'Grains',
  'cereal': 'Grains',
  'oat': 'Grains',
  'wheat': 'Grains',
  'barley': 'Grains',
  
  // Dairy
  'dairy': 'Dairy',
  'milk': 'Dairy',
  'cheese': 'Dairy',
  'yogurt': 'Dairy',
  'yoghurt': 'Dairy',
  'butter': 'Dairy',
  'cream': 'Dairy',
};

export const mapCategory = (openFoodCategory: string | undefined, productName: string | undefined, availableCategories: any[]): string => {
  if (!openFoodCategory && !productName) return '';
  
  // Combine category and product name for better matching
  const searchText = `${openFoodCategory || ''} ${productName || ''}`.toLowerCase();
  
  console.log('Searching for category match in:', searchText);
  
  // Try to match our category mapping
  for (const [key, value] of Object.entries(CATEGORY_MAPPING)) {
    if (searchText.includes(key)) {
      // Find the actual category ID from available categories
      const match = availableCategories.find(cat => 
        cat.name.toLowerCase() === value.toLowerCase()
      );
      if (match) {
        console.log(`Matched "${key}" → "${value}" → Category ID: ${match.id}`);
        return match.id;
      }
    }
  }
  
  // Try direct name matching as fallback
  const directMatch = availableCategories.find(cat => 
    searchText.includes(cat.name.toLowerCase())
  );
  
  if (directMatch) {
    console.log(`Direct match found: ${directMatch.name}`);
  } else {
    console.log('No category match found');
  }
  
  return directMatch?.id || '';
};

export const lookupBarcode = async (barcode: string): Promise<ProductData | null> => {
  try {
    console.log('Looking up barcode:', barcode);
    const response = await fetch(
      `https://world.openfoodfacts.org/api/v2/product/${barcode}.json`
    );
    
    if (!response.ok) {
      console.error('API response not OK:', response.status);
      return null;
    }
    
    const data = await response.json();
    
    if (data.status === 1 && data.product) {
      const product = data.product;
      
      // Extract category information
      let category = '';
      if (product.categories_tags && product.categories_tags.length > 0) {
        // Get the first category and remove language prefix
        category = product.categories_tags[0].replace(/^en:/, '').replace(/-/g, ' ');
      }
      
      const productData: ProductData = {
        barcode: barcode,
        name: product.product_name || product.product_name_en || 'Unknown Product',
        brand: product.brands || undefined,
        category: category || undefined,
        description: product.generic_name || product.ingredients_text_en || undefined,
        imageUrl: product.image_url || product.image_front_url || undefined,
      };
      
      console.log('Product found:', productData);
      return productData;
    }
    
    console.log('Product not found in database');
    return null;
  } catch (error) {
    console.error('Failed to lookup barcode:', error);
    return null;
  }
};

