#!/usr/bin/env python3
"""
Ingest Food & Nutrition knowledge base into the brain system.

Creates:
- 1 umbrella entity (food_nutrition)
- 5 categories (food_groups, nutrients, healthy_eating, food_science, global_foods)
- ~12 concept entities

Usage: python3 ~/wiki/ingest_food_nutrition_knowledge.py [--dry|--query]
"""

import sys
from pathlib import Path
from datetime import date

sys.path.insert(0, str(Path.home() / '.hermes' / 'brain'))
import brain
brain._db_connection = None
brain.init_db()

TODAY = date.today().isoformat()

def ce(content, category, entity_type="food_concept", pinned=False, strength="moderate"):
    return brain.create_entity(
        content=content, entity_type=entity_type, category=category,
        strength=strength, pinned=pinned,
        metadata={"source": "food_nutrition_knowledge_ingest", "date": TODAY},
        log=True,
    )

DATA = {
    "umbrella": {
        "category": "food_nutrition",
        "content": f"""## Food & Nutrition β€” 2nd Grade Knowledge Base

General knowledge about food groups, nutrients, healthy eating habits,
how food grows, and food cultures around the world.

### Domains
- **Food Groups:** The main categories of food and what's in each
- **Nutrients:** What our bodies need from food (vitamins, minerals, protein, etc.)
- **Healthy Eating:** Making good food choices every day
- **Food Science:** Where food comes from and how it's processed
- **Global Foods:** How different cultures eat different things

### Key Concepts
- We need a variety of foods to get all the nutrients our bodies need
- Fruits and vegetables give us vitamins and minerals
- Protein helps our bodies grow and repair
- Grains give us energy
- Dairy gives us calcium for strong bones and teeth
- Water is the most important thing we drink

**Ingested:** {TODAY}
**Source:** Food & nutrition knowledge base (general education)
"""
    },

    "categories": [
        {
            "category": "food_nutrition/food_groups",
            "type": "food_category",
            "content": """## The Food Groups

All food falls into 5 main groups. Eating from all groups keeps you healthy.

### 1. Fruits
- Grow on trees, bushes, or vines
- Usually sweet or tart
- Examples: Apples, bananas, oranges, berries, grapes, watermelon, mangoes
- Rich in vitamin C, fiber, and antioxidants

### 2. Vegetables
- Grow in the ground or above ground
- Examples: Carrots, broccoli, spinach, tomatoes, peppers, potatoes, lettuce
- Rich in vitamins, minerals, and fiber
- Different colored vegetables give different nutrients!

### 3. Grains (Carbohydrates)
- Made from seeds of grasses (wheat, rice, corn, oats)
- Examples: Bread, pasta, rice, cereal, tortillas, crackers, oatmeal
- Give you ENERGY β€” your brain runs on glucose from grains
- Whole grains are better (more fiber and nutrients)

### 4. Protein
- Helps your body GROW and REPAIR muscles
- Animal sources: Meat, poultry, fish, eggs
- Plant sources: Beans, lentils, nuts, seeds, tofu
- Examples: Chicken, beef, fish, eggs, beans, peanut butter, cheese

### 5. Dairy
- Gives you CALCIUM for strong bones and teeth
- Examples: Milk, cheese, yogurt
- Non-dairy calcium sources: Fortified plant milks, leafy greens

### The Plate Method
A simple way to think about a healthy meal:
- Β½ plate = Fruits and Vegetables
- ΒΌ plate = Grains
- ΒΌ plate = Protein
- Plus a serving of Dairy

### What About Other Foods?
- **Fats** β€” Needed in small amounts (avocado, nuts, olive oil)
- **Sugars** β€” Give quick energy but too much is unhealthy
- **Water** β€” Not a food, but essential! Drink 6-8 glasses daily"""
        },
        {
            "category": "food_nutrition/nutrients",
            "type": "food_category",
            "content": """## Nutrients

The things your body gets from food to stay alive, grow, and feel good.

### The 6 Essential Nutrients

**1. Carbohydrates** β€” Your body's main energy source
- Found in: Bread, rice, pasta, fruits, potatoes
- Your brain and muscles run on carbohydrates
- Whole grains give slow, steady energy; sugar gives a quick burst

**2. Proteins** β€” Building blocks for growth and repair
- Found in: Meat, fish, eggs, beans, nuts, cheese
- Made of amino acids (the building blocks)
- Your muscles, skin, hair, and nails are made of protein

**3. Fats** β€” Long-term energy, brain health, vitamin absorption
- Found in: Butter, oil, nuts, avocado, cheese, fish
- Good fats (unsaturated): Olive oil, nuts, fish, avocado
- Bad fats (saturated/trans): Fried foods, processed snacks
- Your brain is 60% fat!

**4. Vitamins** β€” Help your body work properly (need small amounts)
- **Vitamin A** β€” Eyesight (carrots, sweet potatoes)
- **Vitamin B** β€” Energy (whole grains, meat, eggs)
- **Vitamin C** β€” Immune system, healing (oranges, strawberries, bell peppers)
- **Vitamin D** β€” Strong bones (sunlight, fortified milk, fish)
- **Vitamin E** β€” Skin health (nuts, seeds)
- **Vitamin K** β€” Blood clotting (leafy greens)

**5. Minerals** β€” Hard substances that help your body
- **Calcium** β€” Bones and teeth (milk, cheese, yogurt, leafy greens)
- **Iron** β€” Carries oxygen in blood (meat, beans, spinach)
- **Potassium** β€” Heart and muscle function (bananas, potatoes)
- **Zinc** β€” Immune system (meat, beans, whole grains)

**6. Water** β€” Essential for EVERYTHING
- Makes up about 60% of your body
- Carries nutrients, regulates temperature, removes waste
- Drink water throughout the day"""
        },
        {
            "category": "food_nutrition/healthy_eating",
            "type": "food_category",
            "content": """## Healthy Eating Habits

Making smart food choices every day.

### The Healthy Eating Rules

1. **Eat a variety of colors** β€” Different colored fruits and vegetables give different nutrients
2. **Eat breakfast** β€” Fuels your brain for learning all morning
3. **Don't skip meals** β€” Your body needs regular fuel
4. **Drink water** β€” Not soda or juice (too much sugar)
5. **Eat slowly** β€” It takes 20 minutes for your brain to know you're full
6. **Listen to your body** β€” Eat when hungry, stop when full
7. **Limit sugar** β€” Candy and soda are treats, not meals
8. **Eat at home** β€” Home-cooked meals are usually healthier

### Breakfast Ideas
- Oatmeal with fruit
- Eggs and toast
- Yogurt with granola and berries
- Smoothie with fruit and milk

### Lunch Ideas
- Turkey and cheese sandwich with fruit
- Pasta with vegetables and chicken
- Rice, beans, and salad
- Leftovers from dinner!

### Snack Ideas (Good Snacks)
- Fruit (apple, banana, berries)
- Cheese and crackers
- Carrot sticks with hummus
- Yogurt
- Nuts or trail mix
- Hard-boiled eggs

### Foods to Limit
- Candy and sweets (too much sugar)
- Soda and sweet drinks
- Chips and fried foods
- Fast food (too much salt and fat)
- These aren't "forbidden" β€” just enjoy them occasionally as treats!

### Why Healthy Food Matters
- Gives you energy to play and learn
- Helps your body grow tall and strong
- Keeps your brain working well
- Prevents sickness
- Makes your teeth strong"""
        },
        {
            "category": "food_nutrition/food_science",
            "type": "food_category",
            "content": """## Where Food Comes From

All food comes from the Earth β€” either from plants or animals.

### Plant Foods

**From Seeds** β€” Grains, beans, nuts
- Wheat, rice, corn, oats (grains)
- Beans, lentils, peanuts (legumes)
- Almonds, walnuts, cashews (nuts)

**From Fruits** β€” Sweet or tart plant foods
- Apples, oranges, bananas, berries, grapes, watermelon
- Technically: tomatoes, peppers, avocados, cucumbers are fruits too!

**From Vegetables** β€” Different parts of plants
- **Roots:** Carrots, beets, radishes, potatoes
- **Leaves:** Lettuce, spinach, kale, cabbage
- **Stems:** Celery, asparagus
- **Flowers:** Broccoli, cauliflower, artichoke

### Animal Foods

**From Cows** β€” Beef, milk, cheese, butter
**From Chickens** β€” Eggs, chicken meat
**From Sheep** β€” Lamb, wool (not food!)
**From Fish** β€” Salmon, tuna, cod (ocean and lake fish)
**From Bees** β€” Honey, beeswax

### How Food Gets to You

**Farm β†’ Processing β†’ Store β†’ Your Kitchen**

1. **Farming** β€” Grown on farms or caught from the ocean/lake
2. **Processing** β€” Cleaned, packaged, sometimes cooked
3. **Transportation** β€” Trucks, ships, trains carry food
4. **Store** β€” Grocery store, farmer's market
5. **Cooking** β€” Preparing food at home

### Organic vs Conventional
- **Organic** β€” Grown without synthetic pesticides or fertilizers
- **Conventional** β€” Grown with standard farming methods
- Both can be healthy β€” washing produce is important either way

### Food Safety
- Wash fruits and vegetables before eating
- Cook meat thoroughly to kill germs
- Keep food cold in the refrigerator
- Don't leave food out too long (2 hour rule)
- Check expiration dates"""
        },
        {
            "category": "food_nutrition/global_foods",
            "type": "food_category",
            "content": """## Food Around the World

Different cultures eat different foods β€” all of them have their own traditions!

### North America
- Thanksgiving turkey with stuffing and cranberry sauce
- Burgers, hot dogs, apple pie
- Pancakes and waffles for breakfast
- Corn on the cob in summer

### South America
- **Mexico:** Tacos, burritos, enchiladas, guacamole
- **Peru:** Quinoa, potatoes (Peru has 3,000+ types!)
- **Brazil:** Feijoada (bean stew), acai bowls
- Corn and beans are staples throughout

### Europe
- **Italy:** Pasta, pizza, gelato, bread
- **France:** Baguettes, cheese, croissants
- **Greece:** Greek salad, hummus, olive oil
- **England:** Fish and chips, afternoon tea

### Asia
- **China:** Rice, noodles, dumplings, stir-fry
- **India:** Curry, naan bread, rice, lentils (dal)
- **Japan:** Sushi, rice, miso soup, ramen
- **Thailand:** Pad Thai, green curry, mango sticky rice
- Rice is the main food in most Asian countries

### Africa
- **Ethiopia:** Injera (flatbread), lentils, stews
- **Nigeria:** Jollof rice, plantains
- **Morocco:** Couscous, tagine
- Grains, beans, vegetables, and spices

### Australia
- Barbequed meats
- Vegemite (spread made from yeast)
- Seafood (prawns, fish)

### Why Different Foods?
- **Climate** β€” What grows where you live determines what you eat
- **History** β€” Trade routes brought new foods
- **Culture** β€” Families pass down recipes for generations
- **Religion** β€” Some religions have food rules

### Learning About Other Foods
- Try a new food at least 3 times before deciding you don't like it
- Different cuisines use different spices and cooking methods
- Cooking from other cultures is a fun way to learn about them"""
        },
    ],

    "concepts": [
        {
            "category": "food_nutrition/fruits",
            "content": """## Fruits

Sweet and tangy foods that grow on plants.

### Types of Fruits

**Tree Fruits**
- Apples β€” One of the most popular fruits worldwide
- Oranges β€” High in vitamin C
- Bananas β€” Quick energy, high in potassium
- Grapes β€” Grow in bunches, can be dried into raisins
- Peaches, plums, pears, cherries, mangoes

**Berries**
- Strawberries, blueberries, raspberries, blackberries
- Tiny but packed with antioxidants
- Some aren't botanically berries (strawberries) and some are (bananas!)

**Melons**
- Watermelon β€” 92% water, great for staying hydrated
- Cantaloupe, honeydew

**Citrus Fruits**
- Oranges, lemons, limes, grapefruits
- Named after the Latin word for "gift"
- Very high in vitamin C

**Tropical Fruits**
- Pineapple, mango, papaya, kiwi, coconut
- Grow in warm climates
- Often sweet and exotic-tasting

### Why Eat Fruit?
- Natural sweetness (better than candy)
- Fiber helps digestion
- Vitamins and minerals keep you healthy
- Antioxidants protect your body from damage"""
        },
        {
            "category": "food_nutrition/vegetables",
            "content": """## Vegetables

Colorful, nutritious foods that grow in gardens and farms.

### By Color (Each Color = Different Nutrients!)

**Red:** Tomatoes, red peppers, beets, radishes
- Lycopene (heart health) β€” tomatoes

**Orange/Yellow:** Carrots, sweet potatoes, yellow peppers, corn
- Beta-carotene β†’ Vitamin A (good eyesight!)

**Green:** Broccoli, spinach, kale, peas, green beans
- Iron, calcium, vitamin K
- Dark leafy greens are super healthy

**Blue/Purple:** Eggplant, purple cabbage, blue potatoes
- Antioxidants that protect brain cells

**White:** Onions, garlic, cauliflower, mushrooms, potatoes
- Good for immune system and heart

### Parts We Eat
- **Roots:** Carrots, beets, turnips
- **Stems:** Celery, asparagus
- **Leaves:** Lettuce, spinach, kale, cabbage
- **Flowers:** Broccoli, cauliflower
- **Seeds:** Peas, beans, corn
- **Bulbs:** Onions, garlic

### Cooking Vegetables
- **Raw** β€” Crunchy, fresh, keeps all vitamins (salads)
- **Steamed** β€” Soft, keeps nutrients (best method)
- **Roasted** β€” Sweet, crispy edges (in the oven)
- **Sauteed** β€” Quick cooking in a pan with oil"""
        },
        {
            "category": "food_nutrition/grains",
            "content": """## Grains & Carbohydrates

The energy foods β€” fuel for your brain and body.

### What Are Grains?
- Seeds of grass-like plants
- The most widely eaten food in the world
- Made into flour for bread, pasta, and baked goods

### Whole Grains vs Refined Grains

**Whole Grains** (Better!)
- Contains all 3 parts: bran (fiber), germ (nutrients), endosperm (energy)
- Examples: Whole wheat bread, brown rice, oatmeal, quinoa
- More fiber, more vitamins, keeps you full longer

**Refined Grains**
- Only the endosperm is left (white flour)
- Examples: White bread, white rice, regular pasta
- Faster energy but fewer nutrients

### Common Grains
- **Wheat** β€” Bread, pasta, cereal, cakes
- **Rice** β€” White rice, brown rice, sushi rice
- **Corn** β€” Corn on the cob, tortillas, cornmeal
- **Oats** β€” Oatmeal, granola
- **Barley** β€” Soups, stews
- **Quinoa** β€” Technically a seed, but used like a grain

### Why Grains Matter
- Your brain runs on glucose (sugar from carbohydrates)
- Whole grain fiber helps digestion
- Grains are filling and satisfying"""
        },
        {
            "category": "food_nutrition/protein",
            "content": """## Protein

The building blocks of your body.

### What Protein Does
- Builds and repairs muscles
- Makes hair, skin, and nails
- Helps fight infection (antibodies are proteins)
- Helps you feel full longer

### Animal Protein Sources
- **Chicken** β€” Lean, versatile, one of the most eaten meats
- **Beef** β€” Rich in iron and protein
- **Fish** β€” Salmon, tuna, cod (also has healthy omega-3 fats)
- **Eggs** β€” "Complete" protein (all amino acids), cheap and easy
- **Dairy** β€” Milk, cheese, yogurt

### Plant Protein Sources
- **Beans** β€” Black beans, kidney beans, pinto beans
- **Lentils** β€” Small, quick to cook, very nutritious
- **Nuts** β€” Almonds, peanuts, walnuts
- **Seeds** β€” Sunflower, chia, hemp, pumpkin seeds
- **Tofu** β€” Made from soybeans, very versatile
- **Quinoa** β€” Complete protein grain

### How Much Do You Need?
- Kids need about 19-34 grams of protein per day
- That's about 2-3 servings
- One egg = 6 grams of protein
- A handful of beans = 7-8 grams
- A piece of chicken = 20-30 grams"""
        },
        {
            "category": "food_nutrition/dairy",
            "content": """## Dairy & Calcium

The bone-building foods.

### Why Calcium Matters
- Makes bones and teeth strong
- Helps muscles work
- Helps nerves send messages
- Your body is still building bone until you're about 30

### Dairy Foods
- **Milk** β€” Cow's milk (whole, 2%, 1%, skim)
- **Cheese** β€” Cheddar, mozzarella, Swiss, cream cheese
- **Yogurt** β€” Fermented milk, has probiotics (good bacteria)
- **Butter** β€” Mostly fat, very little calcium
- **Ice cream** β€” Tasty but high in sugar (treat, not a health food!)

### Non-Dairy Calcium Sources
- **Fortified plant milks** β€” Soy, almond, oat milk with added calcium
- **Leafy greens** β€” Kale, collard greens, broccoli
- **Fortified cereals and juices**
- **Sardines** β€” Small fish with edible bones
- **Tofu** β€” Made with calcium

### How Much Dairy?
- Kids need about 3 servings of dairy per day
- One serving = 1 cup of milk, 1.5 oz cheese, or 1 cup yogurt
- Drink milk with meals for best absorption"""
        },
        {
            "category": "food_nutrition/cooking",
            "content": """## Cooking Basics

How to prepare food safely and make it taste great.

### Cooking Methods

**Boiling** β€” Cooking in hot water
- Pasta, vegetables, eggs
- Simple and easy

**Baking** β€” Cooking in a hot oven
- Bread, cookies, casseroles, roasted vegetables
- Uses dry heat

**Frying/Sauteing** β€” Cooking in hot oil in a pan
- Quickly cooks food
- Can add flavor but also adds fat

**Grilling/Barbequing** β€” Cooking over an open flame
- Outdoor cooking
- Gives food a smoky flavor

**Steaming** β€” Cooking with hot steam
- Gentle method, keeps nutrients
- Great for vegetables

### Kitchen Safety
- Always wash hands before cooking
- Use a cutting board (never cut directly on the counter)
- Ask an adult to help with knives and the stove
- Use pot holders for hot things
- Keep the kitchen clean

### Simple Recipes Kids Can Help With
- **Pancakes** β€” Mix batter, pour, flip
- **Smoothies** β€” Blend fruit and milk/yogurt
- **Salads** β€” Wash and chop vegetables
- **Sandwiches** β€” Spread, layer, press
- **Trail mix** β€” Combine nuts, seeds, dried fruit"""
        },
    ],
}


def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "--ingest"

    if mode == "--query":
        run_queries()
        return

    if mode == "--dry":
        print(f"=== Food & Nutrition Knowledge Base (DRY RUN) ===")
        print(f"  Total: {1 + len(DATA['categories']) + len(DATA['concepts'])} entities")
        return

    print("=== Food & Nutrition Knowledge Base Ingestion ===")

    umbrella_id = ce(
        DATA["umbrella"]["content"], DATA["umbrella"]["category"],
        entity_type="food_nutrition_umbrella", pinned=True, strength="strong",
    )
    print(f"  βœ… Umbrella: food_nutrition β†’ {umbrella_id[:16]}")

    cat_ids = {}
    for cat in DATA["categories"]:
        cid = ce(cat["content"], cat["category"], entity_type=cat["type"], pinned=True, strength="strong")
        cat_ids[cat["category"]] = cid
        brain.add_edge(cid, "part_of", umbrella_id)
        print(f"  βœ… Category: {cat['category']} β†’ {cid[:16]}")

    for concept in DATA["concepts"]:
        eid = ce(concept["content"], concept["category"])
        for cat_name, cat_id in cat_ids.items():
            if concept["category"].startswith(cat_name):
                brain.add_edge(eid, "part_of", cat_id)
                break
        print(f"  βœ… Concept: {concept['category']} β†’ {eid[:16]}")

    total = 1 + len(DATA["categories"]) + len(DATA["concepts"])
    print(f"\n=== DONE: {total} food & nutrition entities ingested ===")
    run_queries()


def run_queries():
    queries = [
        "food groups fruits vegetables grains",
        "vitamins minerals nutrients",
        "healthy eating breakfast ideas",
        "protein sources animal plant",
        "calcium dairy bones teeth",
        "where food comes from farm",
        "food around world cultures",
        "whole grains vs refined grains",
        "cooking methods boiling baking",
        "fruits vegetables by color",
    ]

    print("\n=== TEST QUERIES ===")
    passed = 0
    for q in queries:
        result = brain.search(q, limit=3)
        hits = len(result) if result else 0
        status = "βœ“" if hits > 0 else "βœ—"
        print(f"  {status} '{q}' β†’ {hits} hits")
        if hits > 0:
            passed += 1
    print(f"\n  Results: {passed}/{len(queries)} queries returned hits")


if __name__ == "__main__":
    main()