#!/usr/bin/env python3
"""
Ingest Human Body knowledge base into the brain system.

Creates:
- 1 umbrella entity (human_body)
- 5 categories (systems, senses, skeleton_muscles, health_hygiene, growth_development)
- ~14 concept entities

Usage: python3 ~/wiki/ingest_human_body_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="human_body_concept", pinned=False, strength="moderate"):
    return brain.create_entity(
        content=content, entity_type=entity_type, category=category,
        strength=strength, pinned=pinned,
        metadata={"source": "human_body_knowledge_ingest", "date": TODAY},
        log=True,
    )

DATA = {
    "umbrella": {
        "category": "human_body",
        "content": f"""## Human Body — 2nd Grade Knowledge Base

General knowledge about the human body: body systems, senses, skeleton, muscles,
and how to keep our bodies healthy.

### Domains
- **Body Systems:** How our body works — heart, lungs, digestion, brain
- **The Five Senses:** Sight, hearing, touch, taste, smell
- **Skeleton & Muscles:** Bones, muscles, and movement
- **Health & Hygiene:** Keeping our bodies clean and healthy
- **Growth & Development:** How we grow and change

### Key Concepts
- The body has systems that work together to keep us alive
- We have 5 senses that help us understand the world
- Our skeleton gives us structure, muscles help us move
- Good habits (exercise, healthy food, sleep, hygiene) keep us healthy
- We grow from babies into children, then adults

**Ingested:** {TODAY}
**Source:** Human body knowledge base (general education)
**Note:** Five senses mentioned in Science curriculum Week 1
"""
    },

    "categories": [
        {
            "category": "human_body/systems",
            "type": "human_body_category",
            "content": """## Body Systems

Your body has several systems that work together — like a team.

### Circulatory System — Heart & Blood
- The **heart** pumps blood through your body
- Blood carries oxygen and nutrients to every cell
- Your heart beats about 100,000 times per day!
- Blood vessels (arteries and veins) are like pipes that carry blood

### Respiratory System — Lungs & Breathing
- **Lungs** take in oxygen from the air you breathe
- When you breathe in → oxygen enters your lungs
- When you breathe out → carbon dioxide leaves your body
- You breathe about 20,000 times per day without thinking about it!

### Digestive System — Breaking Down Food
- Food travels: Mouth → Esophagus → Stomach → Small Intestine → Large Intestine
- **Mouth** — Chewing breaks food into smaller pieces, saliva starts digestion
- **Stomach** — Mixes food with acids to break it down
- **Small intestine** — Absorbs nutrients into the blood
- **Large intestine** — Absorbs water, makes waste

### Nervous System — Brain & Nerves
- The **brain** is the control center — it tells your body what to do
- **Nerves** carry messages between the brain and the rest of the body
- When you touch something hot, nerves tell your brain FAST, and your brain tells your hand to pull away
- The brain also controls thinking, remembering, and feeling

### Musculoskeletal System — Bones & Muscles
- **Skeleton** — Your internal frame (206 bones when you're an adult!)
- **Muscles** — Attached to bones, they pull to make you move
- **Joints** — Where two bones meet (knees, elbows, shoulders, hips)

### How Systems Work Together
When you run:
1. Brain says "go!" (nervous system)
2. Muscles pull on bones (musculoskeletal)
3. You breathe faster (respiratory)
4. Heart pumps faster (circulatory)
5. Stomach gets nutrients to muscles (digestive)"""
        },
        {
            "category": "human_body/senses",
            "type": "human_body_category",
            "content": """## The Five Senses

How we experience and understand the world around us.

### 1. Sight (Eyes)
- Eyes let us see colors, shapes, and movement
- Light enters the eye and sends messages to the brain
- We have two eyes — this helps us see depth (distance)
- **Eye parts:** Eyelid (protects), pupil (lets light in), iris (gives eye color)
- **Care:** Don't stare at the sun, take breaks from screens

### 2. Hearing (Ears)
- Ears let us hear sounds — music, voices, birds, cars
- Sound waves enter the ear and move tiny bones inside
- The ear has three parts: outer ear, middle ear, inner ear
- **Care:** Don't put things in your ears, protect from very loud sounds

### 3. Touch (Skin)
- Skin is the LARGEST organ in your body!
- Touch lets us feel: soft/hard, hot/cold, wet/dry, rough/smooth
- Special nerve endings in the skin send messages to the brain
- **Care:** Use sunscreen, wash your skin, keep it moisturized

### 4. Taste (Tongue)
- Your tongue detects 5 basic tastes: Sweet, Sour, Salty, Bitter, Umami
- Taste buds are on your tongue — you have about 10,000 of them!
- Taste works together with smell — that's why food tastes bland when you have a cold
- Different areas of the tongue detect different tastes

### 5. Smell (Nose)
- Your nose can detect millions of different smells
- Smell is strongly connected to memory — a smell can remind you of something
- Smell works with taste to help us enjoy food
- **Care:** Avoid strong chemicals, keep nose clean

### Why Senses Matter
- Senses help us stay safe (hearing a car coming, touching something hot)
- Senses help us learn (reading uses sight, listening uses hearing)
- Senses help us enjoy life (music, food, hugs, flowers)"""
        },
        {
            "category": "human_body/skeleton",
            "type": "human_body_category",
            "content": """## The Skeleton

The framework inside your body that gives you shape and protects you.

### What the Skeleton Does
- **Support** — Holds your body up (without bones, you'd be a pile of jelly!)
- **Protection** — Shields your important organs
- **Movement** — Muscles pull on bones to make you move
- **Growth** — Bones grow as you grow

### How Many Bones?
- Babies are born with about 270 bones
- Some bones fuse together as you grow
- Adults have 206 bones

### Major Bones

**Skull** — Protects your brain
- Made of 22 bones that fuse together
- Protects your most important organ!

**Rib Cage** — Protects your heart and lungs
- 24 ribs attached to your spine and breastbone
- You can feel them under your skin

**Spine (Backbone)** — Supports your body
- Made of 33 small bones called vertebrae
- Lets you bend and twist

**Femur** — Thigh bone, longest bone in the body
**Humerus** — Upper arm bone
**Tibia** — Shin bone (lower leg)

### Joints
Joints are where two bones meet:
- **Hinge joint** — Opens one way (knee, elbow)
- **Ball-and-socket joint** — Moves in all directions (shoulder, hip)
- **Pivot joint** — Rotates (neck, between forearm bones)

### Fun Facts
- Your fingernails are made of the same material as toenails (keratin)
- Your smallest bones are in your ears (stirrup bone)
- Your nose and ears never stop growing!"""
        },
        {
            "category": "human_body/muscles",
            "type": "human_body_category",
            "content": """## Muscles

The tissues that make your body move — you have about 600 of them!

### What Muscles Do
- **Move your body** — Attached to bones, they contract (shorten) to pull bones
- **Keep you warm** — Shivering is muscles working fast to make heat
- **Keep organs working** — Your heart is a muscle that never stops
- **Control body openings** — Muscles control blinking, swallowing, etc.

### Types of Muscles

**Skeletal Muscles** — The ones YOU control
- Attached to bones
- You decide when to use them (voluntary)
- Examples: Biceps (arm), quadriceps (thigh), calves
- When one muscle contracts, its partner relaxes

**Smooth Muscles** — Work WITHOUT you thinking
- Inside your stomach, intestines, blood vessels
- They move food through your digestive system
- You can't control them (involuntary)

**Heart Muscle (Cardiac)** — Only in your heart
- Never stops working
- Beats about 100,000 times per day
- The ONLY muscle that works without rest

### Major Muscles You Can Feel
- **Biceps** — Front of upper arm (flex your arm)
- **Triceps** — Back of upper arm
- **Quadriceps** — Front of thigh
- **Calf muscles** — Back of lower leg
- **Abs** — Stomach muscles
- **Chest muscles** — Push things away from you

### How Muscles Work
- Muscles work in pairs — one pulls, one pushes back
- When you bend your arm: biceps contracts, triceps relaxes
- Exercise makes muscles stronger (they grow bigger and more powerful)
- Muscles need food (protein) and rest to grow"""
        },
        {
            "category": "human_body/health_hygiene",
            "type": "human_body_category",
            "content": """## Health & Hygiene

Keeping your body clean, healthy, and strong.

### Personal Hygiene

**Washing Your Hands**
- Before eating, after using the bathroom, after playing outside
- Use soap and warm water, scrub for 20 seconds
- Prevents germs from spreading

**Brushing Your Teeth**
- Twice a day (morning and night)
- Brush for 2 minutes
- Prevents cavities and keeps breath fresh
- Replace your toothbrush every 3-4 months

**Bathing/Showers**
- Wash your whole body with soap and water
- Wash hair with shampoo
- Prevents body odor and removes germs

**Other Habits**
- Trim fingernails regularly
- Use clean clothes daily
- Cover your mouth when you cough or sneeze

### Staying Healthy

**Exercise**
- At least 60 minutes of physical activity each day
- Running, jumping, swimming, dancing, biking, sports
- Makes your heart stronger, muscles bigger, bones denser

**Sleep**
- Kids your age need 9-12 hours of sleep per night
- During sleep, your body grows and repairs itself
- Being tired affects your mood and learning

**Healthy Food**
- Eat a variety of fruits and vegetables
- Drink plenty of water (8 glasses a day)
- Limit sugary snacks and sodas

### Germs & Immunity
- Germs (bacteria and viruses) are tiny organisms
- Some germs make you sick
- Your immune system fights germs
- Vaccines train your immune system to fight specific germs
- Washing hands and covering coughs prevents spreading germs"""
        },
    ],

    "concepts": [
        {
            "category": "human_body/heart",
            "content": """## The Heart

Your body's pump — it never stops working.

### Key Facts
- Size of your fist
- Beats about 100,000 times per day
- Pumps about 2,000 gallons of blood per day
- Located in your chest, slightly to the left

### What the Heart Does
- Receives blood from your body (without oxygen)
- Sends blood to lungs (to get oxygen)
- Receives fresh oxygenated blood from lungs
- Pumps it out to every part of your body

### Heartbeat
- You can feel your heartbeat by putting two fingers on your wrist
- A heartbeat goes "lub-dub" — two sounds
- Exercise makes your heart beat faster
- When you rest, it slows down

### Keeping Your Heart Healthy
- Exercise regularly (running, swimming, dancing)
- Eat healthy foods (fruits, vegetables, whole grains)
- Don't smoke (secondhand smoke is also bad)
- Get enough sleep"""
        },
        {
            "category": "human_body/lungs",
            "content": """## The Lungs

Your body's air exchange system — breathing without thinking.

### Key Facts
- You have two lungs (left is smaller to make room for the heart)
- Made of tiny sacs called alveoli (about 300 million!)
- If you spread out all your alveoli, they'd cover a tennis court
- You breathe about 20,000 times per day

### How Breathing Works
1. **Breathe IN** — Diaphragm muscle pulls down, lungs expand, air flows in
2. **Oxygen** enters tiny blood vessels in your lungs
3. **Blood** carries oxygen to every cell in your body
4. **Cells** use oxygen to make energy
5. **Breathe OUT** — Diaphragm relaxes, lungs shrink, push out carbon dioxide

### Air You Breathe
- The air we breathe is mostly nitrogen and oxygen
- Oxygen is what our bodies need
- Carbon dioxide is waste — we breathe it out
- Clean air is important — pollution hurts lungs

### Keeping Lungs Healthy
- Don't smoke or breathe secondhand smoke
- Exercise to make your lungs stronger
- Avoid breathing polluted air
- Deep breathing exercises are good for you"""
        },
        {
            "category": "human_body/brain",
            "content": """## The Brain

The most amazing organ — your body's control center.

### Key Facts
- Weighs about 3 pounds (like a cantaloupe)
- Has about 86 billion neurons (nerve cells)
- Uses 20% of your body's energy
- Made of soft tissue — protected by your skull

### What the Brain Does

**Controls Your Body**
- Tells muscles when to move
- Controls your heartbeat and breathing
- Regulates your body temperature

**Thinking & Learning**
- Solves problems
- Remembers things
- Makes decisions
- Learns new skills (reading, math, riding a bike)

**Feelings & Emotions**
- Happy, sad, angry, scared, excited
- Your brain creates all your feelings
- Emotions help you make decisions

**Processing Senses**
- Information from eyes, ears, nose, tongue, and skin all goes to the brain
- Your brain decides what it all means

### Brain Parts
- **Cerebrum** — Largest part, handles thinking and learning
- **Cerebellum** — Controls balance and coordination
- **Brain stem** — Controls breathing and heartbeat

### Keeping Your Brain Healthy
- Learn new things (reading, puzzles, games)
- Get enough sleep (brain processes memories during sleep)
- Eat healthy food (brain needs good fuel)
- Exercise (more blood flow to the brain)"""
        },
        {
            "category": "human_body/digestion",
            "content": """## Digestion

How your body turns food into energy and building materials.

### The Digestive Journey

1. **Mouth** — You chew food, saliva starts breaking it down
2. **Esophagus** — A tube that carries food from mouth to stomach
3. **Stomach** — Mixes food with acids, turns it into a liquid paste
4. **Small Intestine** — 20 feet long! Absorbs nutrients into your blood
5. **Large Intestine** — Absorbs water, turns waste solid
6. **Exit** — Waste leaves the body

### What Happens to Food
- **Carbohydrates** (bread, pasta, fruit) → Energy
- **Proteins** (meat, beans, eggs) → Building blocks for muscles
- **Fats** (butter, oil, nuts) → Long-term energy storage
- **Vitamins & Minerals** → Help your body work properly
- **Water** → Keeps everything running smoothly

### How Long Does It Take?
- Stomach digestion: 2-4 hours
- Small intestine: 2-6 hours
- Large intestine: 12-36 hours
- Total: About 24-72 hours from eating to waste

### Keeping Digestion Healthy
- Eat fiber (fruits, vegetables, whole grains)
- Drink plenty of water
- Chew your food slowly
- Don't eat too fast or too much at once"""
        },
        {
            "category": "human_body/blood",
            "content": """## Blood

The liquid that keeps you alive — flowing through your body 24/7.

### What Blood Does
- Carries oxygen from lungs to every cell
- Carries nutrients from food to every cell
- Carries away waste products
- Fights germs (white blood cells)
- Stops bleeding (clotting)

### Parts of Blood

**Red Blood Cells** — Carry oxygen
- Reddish color (from iron)
- Billions of them in your body
- Made in your bones

**White Blood Cells** — Fight infection
- Part of your immune system
- Destroy germs that get into your body
- You have more when you're sick

**Platelets** — Stop bleeding
- Tiny cell pieces that clot blood
- When you get a cut, platelets plug the hole

**Plasma** — The liquid part
- Mostly water
- Carries cells, nutrients, and hormones

### Fun Facts
- Adults have about 1 gallon of blood
- Your blood travels through about 60,000 miles of blood vessels
- It takes about 1 minute for blood to make one complete trip through your body
- Your body replaces about 2 million red blood cells every second"""
        },
        {
            "category": "human_body/skin",
            "content": """## Skin

Your body's largest organ — your first line of defense.

### Key Facts
- Covers your entire body
- About 20 square feet in adults
- Made of 3 layers: epidermis (outer), dermis (middle), subcutaneous (deep)
- Contains nerves, blood vessels, hair follicles, and sweat glands

### What Skin Does
- **Protection** — Keeps germs and water out
- **Sensation** — Lets you feel touch, temperature, pain
- **Temperature control** — Sweating cools you down
- **Vitamin D** — Made when skin is exposed to sunlight
- **Waterproof** — Keeps your insides from drying out

### What's on Your Skin
- **Hair** — Grows from follicles, protects from sun
- **Fingernails** — Made of keratin, protect fingertips
- **Sweat** — Cools you down through evaporation
- **Natural oils** — Keep skin soft and waterproof

### Skin Care
- Wash with soap and water
- Use sunscreen in the sun
- Keep wounds clean to prevent infection
- Drink water to keep skin healthy"""
        },
        {
            "category": "human_body/growth",
            "content": """## Growth & Development

How we grow from babies into adults.

### Stages of Growth

**Baby (0-1 years)**
- Born about 20 inches long, 7 pounds
- Learns to smile, roll over, sit up, crawl
- First steps around 12 months
- First words around 12 months

**Toddler (1-3 years)**
- Learns to walk, run, climb
- Vocabulary grows fast (from a few words to hundreds)
- Learns to use the toilet
- Very curious — asks "why?" a lot

**Early Childhood (3-6 years)**
- Better coordination (jumping, hopping, balancing)
- Learns to read and write
- Makes friends, plays with others
- Grows about 2-3 inches per year

**Middle Childhood (6-12 years)** — Where you are now!
- Better at complex tasks (reading, math, sports)
- Grows about 2 inches per year
- Loses baby teeth, adult teeth come in
- Thinking becomes more logical

**Teenager (12-18 years)**
- Growth spurts (grow very fast!)
- Body changes (puberty)
- Voice changes (especially for boys)
- Thinking becomes more abstract

**Adult (18+ years)**
- Growth stops
- Fully developed body and brain
- Can have their own children

### What Makes Us Grow
- **Genes** — Inherited from parents (determines how tall, eye color, etc.)
- **Nutrition** — Food gives your body building materials
- **Sleep** — Growth hormone is released during deep sleep
- **Exercise** — Makes bones and muscles strong"""
        },
    ],
}


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

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

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

    print("=== Human Body Knowledge Base Ingestion ===")

    umbrella_id = ce(
        DATA["umbrella"]["content"], DATA["umbrella"]["category"],
        entity_type="human_body_umbrella", pinned=True, strength="strong",
    )
    print(f"  ✅ Umbrella: human_body → {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} human body entities ingested ===")
    run_queries()


def run_queries():
    queries = [
        "heart blood circulation",
        "lungs breathing respiratory",
        "brain nervous system neurons",
        "digestion stomach food",
        "five senses eyes ears",
        "skeleton bones joints",
        "muscles types skeletal",
        "personal hygiene washing hands",
        "blood cells red white platelets",
        "skin largest organ",
        "growth development stages",
    ]

    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()