from typing import Dict, List
import requests
from config import get_config

config = get_config()

class NutritionService:
    
    # USDA API endpoint
    USDA_API_URL = "https://fdc.nal.usda.gov/api/foods/search"
    API_KEY = "https://fdc.nal.usda.gov/api-key-signup"  
   
    NUTRITION_DATABASE = {
        "chicken": {"calories": 165, "protein": 31, "fat": 3.6, "carbs": 0, "fiber": 0},
        "tomato": {"calories": 18, "protein": 0.9, "fat": 0.2, "carbs": 3.9, "fiber": 1.2},
        "pasta": {"calories": 131, "protein": 5, "fat": 1.1, "carbs": 25, "fiber": 1.8},
        "rice": {"calories": 130, "protein": 2.7, "fat": 0.3, "carbs": 28, "fiber": 0.4},
        "olive oil": {"calories": 884, "protein": 0, "fat": 100, "carbs": 0, "fiber": 0},
        "garlic": {"calories": 149, "protein": 6.4, "fat": 0.5, "carbs": 33, "fiber": 2.1},
        "onion": {"calories": 40, "protein": 1.1, "fat": 0.1, "carbs": 9, "fiber": 1.7},
        "mushroom": {"calories": 22, "protein": 3.3, "fat": 0.3, "carbs": 3.3, "fiber": 1},
        "broccoli": {"calories": 34, "protein": 2.8, "fat": 0.4, "carbs": 7, "fiber": 2.4},
        "carrot": {"calories": 41, "protein": 0.9, "fat": 0.2, "carbs": 10, "fiber": 2.8},
        "lettuce": {"calories": 15, "protein": 1.2, "fat": 0.3, "carbs": 3, "fiber": 2},
        "egg": {"calories": 155, "protein": 13, "fat": 11, "carbs": 1.1, "fiber": 0},
        "milk": {"calories": 64, "protein": 3.2, "fat": 3.3, "carbs": 4.8, "fiber": 0},
        "flour": {"calories": 364, "protein": 10, "fat": 1, "carbs": 76, "fiber": 2.7},
        "butter": {"calories": 717, "protein": 0.9, "fat": 81, "carbs": 0.1, "fiber": 0},
        "parmesan": {"calories": 431, "protein": 38, "fat": 29, "carbs": 1.2, "fiber": 0},
        "bell pepper": {"calories": 31, "protein": 1, "fat": 0.3, "carbs": 6, "fiber": 2},
        "soy sauce": {"calories": 61, "protein": 11, "fat": 0.6, "carbs": 5.6, "fiber": 0.8},
        "ginger": {"calories": 80, "protein": 1.8, "fat": 0.8, "carbs": 18, "fiber": 2.2},
        "maple syrup": {"calories": 260, "protein": 0, "fat": 0.1, "carbs": 67, "fiber": 0},
        "baking powder": {"calories": 163, "protein": 0, "fat": 0, "carbs": 37, "fiber": 0},
        "basil": {"calories": 23, "protein": 3.1, "fat": 0.6, "carbs": 3, "fiber": 1.3},
        "lemon": {"calories": 29, "protein": 1.1, "fat": 0.3, "carbs": 9, "fiber": 2.8},
        "broth": {"calories": 15, "protein": 1.5, "fat": 0.5, "carbs": 0.5, "fiber": 0},
    }
    
    def __init__(self):
        self.db = self.NUTRITION_DATABASE
    
    def get_nutrition_info(self, ingredient: str, quantity: float = 100) -> Dict:
     
        ingredient_lower = ingredient.lower().strip()
        
        if ingredient_lower in self.db:
            nutrition = self.db[ingredient_lower].copy()
            scale = quantity / 100
            for key in nutrition:
                nutrition[key] = round(nutrition[key] * scale, 2)
            return nutrition
        else:
            for key in self.db.keys():
                if key in ingredient_lower or ingredient_lower in key:
                    nutrition = self.db[key].copy()
                    scale = quantity / 100
                    for k in nutrition:
                        nutrition[k] = round(nutrition[k] * scale, 2)
                    return nutrition
            return {
                "calories": 0,
                "protein": 0,
                "fat": 0,
                "carbs": 0,
                "fiber": 0,
                "source": "estimate"
            }
    
    def analyze_recipe(self, ingredients: List[str], servings: int = 1) -> Dict:
        
        total_nutrition = {
            "calories": 0,
            "protein": 0,
            "fat": 0,
            "carbs": 0,
            "fiber": 0
        }
        
        ingredient_details = []
        
        for ingredient in ingredients:
            parts = ingredient.split()
            quantity = 100  
            ingredient_name = ingredient
            for i, part in enumerate(parts):
                if part.replace('.', '', 1).isdigit():
                    quantity = float(part)
                    ingredient_name = ' '.join(parts[i+1:]) if i+1 < len(parts) else ingredient_name
                    break
            
            nutrition = self.get_nutrition_info(ingredient_name, quantity)
            ingredient_details.append({
                "ingredient": ingredient,
                "nutrition": nutrition
            })
        
            for key in total_nutrition:
                total_nutrition[key] += nutrition.get(key, 0)
        
        per_serving = {}
        for key in total_nutrition:
            per_serving[key] = round(total_nutrition[key] / servings, 2)
        
        return {
            "total_nutrition": {k: round(v, 2) for k, v in total_nutrition.items()},
            "per_serving": per_serving,
            "servings": servings,
            "ingredients_nutrition": ingredient_details
        }
    
    def get_daily_value_percentages(self, nutrition: Dict, serving_type: str = "total") -> Dict:

        values = nutrition.get(serving_type, nutrition)
        
        dv_values = {
            "calories": 2000,
            "protein": 50,
            "fat": 78,
            "carbs": 300,
            "fiber": 25
        }
        
        percentages = {}
        for key, value in values.items():
            if key in dv_values and dv_values[key] > 0:
                percentages[key] = round((value / dv_values[key]) * 100, 1)
            else:
                percentages[key] = 0
        
        return percentages
    
    def get_nutrition_summary(self, nutrition_analysis: Dict) -> str:
        per_serving = nutrition_analysis["per_serving"]
        servings = nutrition_analysis["servings"]
        
        summary = f"Nutrition per serving ({servings} servings):\n"
        summary += f"• Calories: {per_serving['calories']} kcal\n"
        summary += f"• Protein: {per_serving['protein']}g\n"
        summary += f"• Fat: {per_serving['fat']}g\n"
        summary += f"• Carbohydrates: {per_serving['carbs']}g\n"
        summary += f"• Fiber: {per_serving['fiber']}g\n"
        
        return summary


# Global instance
nutrition_service = None

def get_nutrition_service() -> NutritionService:

    global nutrition_service
    if nutrition_service is None:
        nutrition_service = NutritionService()
    return nutrition_service