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

Focuses on animal classification, characteristics, and life cycles.
Avoids duplicating habitat/ecosystem content (covered in science curriculum).

Creates:
- 1 umbrella entity (animals)
- 6 category entities (groups, vertebrates, invertebrates, life_cycles, adaptations, habitats)
- ~25 concept entities

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


DATA = {
    "umbrella": {
        "category": "animals",
        "content": f"""## Animals — 2nd Grade Knowledge Base

General knowledge about animal groups, characteristics, life cycles, and adaptations.
Complements the science curriculum (which covers habitats and ecosystems) by providing
the classification framework — what makes each animal group different.

### Domains
- **Animal Groups:** Mammals, birds, reptiles, amphibians, fish, insects
- **Vertebrates vs Invertebrates:** Animals with and without backbones
- **Life Cycles:** How animals grow and develop
- **Adaptations:** How animals survive in their environments
- **Animal Behavior:** How animals live, hunt, and communicate

### Key Concepts
- Animals are classified by shared characteristics (fur, feathers, scales, etc.)
- Vertebrates have backbones; invertebrates don't
- All animals need food, water, and shelter
- Animals have different life cycles (egg → larva → adult, etc.)
- Adaptations help animals survive (camouflage, hibernation, migration)

**Ingested:** {TODAY}
**Source:** Animals knowledge base (general education)
**Note:** Habitats/ecosystems covered in science curriculum (weeks 17-20, 28-29)
"""
    },

    "categories": [
        {
            "category": "animals/classification",
            "type": "animals_category",
            "content": """## Animal Classification

How scientists organize and group animals based on shared characteristics.

### The Two Main Groups

**Vertebrates** — Animals with a backbone/spine
- Mammals, Birds, Reptiles, Amphibians, Fish
- Have an internal skeleton
- Usually larger and more complex

**Invertebrates** — Animals WITHOUT a backbone
- Insects, Spiders, Worms, Snails, Jellyfish, Starfish
- Make up about 95% of all animal species!
- Can still be very complex and interesting

### The 5 Major Animal Groups (Vertebrates)
1. **Mammals** — Have fur/hair, drink milk as babies, warm-blooded
2. **Birds** — Have feathers, lay eggs, most can fly, warm-blooded
3. **Reptiles** — Have scales, lay eggs on land, cold-blooded
4. **Amphibians** — Start in water, grow to live on land, moist skin
5. **Fish** — Live in water, have gills and scales, cold-blooded

### How to Identify Animals
Ask these questions:
1. Does it have a backbone? → Vertebrate or Invertebrate
2. What covers its body? → Fur (mammal), Feathers (bird), Scales (reptile/fish), Moist skin (amphibian)
3. Where does it live? → Land, Water, or Both
4. How is it born? → Live birth (most mammals) or Eggs (most others)
5. Is it warm or cold-blooded? → Warm-blooded (mammals, birds) or Cold-blooded (others)"""
        },
        {
            "category": "animals/vertebrates",
            "type": "animals_category",
            "content": """## Vertebrates

Animals with a backbone — the five major groups we study.

### What Makes a Vertebrate?
- Has a backbone (spine) made of bones
- Has an internal skeleton
- Usually has a brain and complex organs
- All vertebrates are chordates (a larger animal group)

### The 5 Groups at a Glance

| Group | Body Cover | Temperature | Babies | Breathes With |
|-------|-----------|-------------|--------|---------------|
| Mammals | Fur/Hair | Warm-blooded | Live birth (usually) | Lungs |
| Birds | Feathers | Warm-blooded | Eggs | Lungs |
| Reptiles | Scales | Cold-blooded | Eggs (on land) | Lungs |
| Amphibians | Moist skin | Cold-blooded | Eggs (in water) | Gills → Lungs |
| Fish | Scales | Cold-blooded | Eggs (in water) | Gills |

### Key Differences
- **Warm-blooded** (mammals, birds): Body stays the same temperature regardless of outside temperature
- **Cold-blooded** (reptiles, amphibians, fish): Body temperature changes with the environment — they need to sunbathe to warm up!
- **Lungs** vs **Gills**: Lungs breathe air, gills extract oxygen from water"""
        },
        {
            "category": "animals/invertebrates",
            "type": "animals_category",
            "content": """## Invertebrates

Animals without a backbone — the majority of all animal life.

### What Makes an Invertebrate?
- NO backbone or internal skeleton
- May have an exoskeleton (hard outer shell) instead
- Usually smaller than vertebrates
- About 95% of all animal species are invertebrates!

### Major Groups

**Insects** — 6 legs, 3 body parts, often wings
- Ants, bees, butterflies, beetles, flies, grasshoppers, ladybugs
- Largest group of animals on Earth

**Arachnids** — 8 legs, 2 body parts
- Spiders, scorpions, ticks, mites

**Crustaceans** — Hard shell, live in water
- Crabs, lobsters, shrimp, barnacles

**Mollusks** — Soft body, often with a shell
- Snails, slugs, clams, oysters, octopus, squid

**Worms** — Long, soft bodies
- Earthworms, leeches, flatworms

**Echinoderms** — Spiny skin, 5-part symmetry
- Starfish, sea urchins, sand dollars

**Others**
- Jellyfish (simple, no brain)
- Sponges (simplest animals)"""
        },
        {
            "category": "animals/life_cycles",
            "type": "animals_category",
            "content": """## Animal Life Cycles

How animals grow and develop from baby to adult.

### What Is a Life Cycle?
A life cycle is the series of changes an animal goes through from birth to adulthood.
All animals reproduce to create new generations.

### Types of Life Cycles

**Direct Development** (simple — baby looks like smaller adult)
- Most mammals: Baby → Juvenile → Adult
- Example: A puppy grows into a dog
- Example: A human baby grows into an adult

**Metamorphosis** (dramatic change — baby looks very different from adult)
- Complete metamorphosis: Egg → Larva → Pupa → Adult (4 stages)
  - Butterflies: Egg → Caterpillar → Chrysalis → Butterfly
  - Frogs: Egg → Tadpole → Froglet → Frog
- Incomplete metamorphosis: Egg → Nymph → Adult (3 stages)
  - Grasshoppers: Egg → Young grasshopper → Adult
  - Dragonflies

### Animal Reproduction
- **Egg-layers (Oviparous):** Birds, most reptiles, amphibians, fish, insects
- **Live birth (Viviparous):** Most mammals (whales, dogs, cats, humans)
- **Both:** Some reptiles and sharks give live birth

### Life Span Variations
- Fruit fly: About 30 days
- Mouse: 2-3 years
- Dog: 10-15 years
- Elephant: 60-70 years
- Giant tortoise: 100+ years"""
        },
        {
            "category": "animals/adaptations",
            "type": "animals_category",
            "content": """## Animal Adaptations

Special features or behaviors that help animals survive.

### What Is an Adaptation?
An adaptation is a feature or behavior that helps an animal survive in its environment.
Adaptations develop over many generations through natural selection.

### Physical Adaptations (Body Features)

**Camouflage** — Blending in with surroundings
- Chameleons change color
- Arctic fox turns white in winter
- Stick insects look like twigs

**Protective Coverings**
- Porcupine quills
- Turtle shell
- Crab shell
- Armadillo armor

**Specialized Body Parts**
- Eagle's sharp talons for catching prey
- Giraffe's long neck for reaching tall trees
- Whale's blubber for staying warm
- Bird beaks shaped differently for different foods

### Behavioral Adaptations (Actions)

**Hibernation** — Deep sleep through winter
- Bears, groundhogs, bats
- Body temperature drops, heartbeat slows
- Animal lives off stored body fat

**Migration** — Traveling long distances seasonally
- Birds flying south for winter
- Monarch butterflies to Mexico
- Wildebeest in Africa

**Nocturnal** — Active at night
- Owls, bats, owlets, hedgehogs
- Avoids daytime heat and predators

**Playing Dead** — Pretending to be dead
- Opossums, some snakes and beetles
- Predators often lose interest in "dead" prey"""
        },
    ],

    "concepts": [
        {
            "category": "animals/group/mammals",
            "content": """## Mammals

Warm-blooded animals with fur or hair that drink milk as babies.

### Key Characteristics
- Have fur, hair, or both
- Warm-blooded (constant body temperature)
- Drink milk from mother when babies (mammary glands)
- Most give birth to live young (not eggs)
- Breathe with lungs
- Have a backbone (vertebrates)
- Most have teeth

### Major Types

**Land Mammals**
- Dogs, cats, horses, cows, elephants, giraffes, lions, tigers, bears, rabbits

**Marine Mammals** (live in water but breathe air)
- Whales, dolphins, seals, sea lions, manatees, walruses

**Flying Mammals**
- Bats (the ONLY mammals that can truly fly)

**Aquatic Mammals** (freshwater)
- Beavers, otters, platypus (lays eggs — one of only two monotremes!)

### Interesting Facts
- The blue whale is the largest animal ever (bigger than any dinosaur!)
- A kangaroo can't walk backward
- Elephants can't jump
- The platypus is a mammal but lays eggs
- Humans are mammals too!
- There are about 6,500 species of mammals"""
        },
        {
            "category": "animals/group/birds",
            "content": """## Birds

Warm-blooded vertebrates with feathers, beaks, and hard-shelled eggs.

### Key Characteristics
- Have feathers (unique to birds — nothing else has them!)
- Lay hard-shelled eggs
- Have beaks (no teeth)
- Most can fly
- Warm-blooded
- Have wings
- Breathe with lungs

### Bird Adaptations

**Flight Adaptations**
- Hollow bones (lighter for flying)
- Strong chest muscles
- Streamlined body shape
- Wings for lift

**Beak Types** (matched to diet)
- Hooked beaks → Carnivores (eagles, hawks) — tearing meat
- Thin, pointed beaks → Insect-eaters (warblers)
- Thick, short beaks → Seed-eaters (finches)
- Long, thin beaks → Nectar-drinkers (hummingbirds)
- Filter beaks → Straining water (flamingos)

### Major Types

**Songbirds** — Sing for territory and mates
- Robins, sparrows, blue jays, cardinals, warblers

**Water Birds** — Live near or on water
- Ducks, geese, swans, herons, penguins (flightless!)

**Birds of Prey** — Hunt for food
- Eagles, hawks, owls, falcons

**Flightless Birds**
- Ostrich (largest bird), penguin, kiwi, emu

### Fun Facts
- The hummingbird can fly backward
- Owls can turn their heads 270 degrees
- Penguins can't fly but are excellent swimmers
- A group of geese is called a "gaggle"
- Chickens are descendants of the T-Rex (theropod dinosaur)"""
        },
        {
            "category": "animals/group/reptiles",
            "content": """## Reptiles

Cold-blooded animals with scales that lay eggs on land.

### Key Characteristics
- Have dry, scaly skin
- Cold-blooded (need sun to warm up)
- Lay eggs with leathery shells on land
- Breathe with lungs (even aquatic ones!)
- Have a backbone (vertebrates)

### Major Types

**Lizards** — Largest reptile group
- Geckos, iguanas, chameleons, monitors
- Most have 4 legs (some have none, like snakes)
- Some can drop their tail when grabbed (regenerates later)

**Snakes** — Legless reptiles
- No legs, move by slithering
- Use tongues to "smell" their environment
- Some are venomous, most are not
- Constrictors squeeze prey; venomous snakes inject poison

**Turtles & Tortoises**
- Have hard shells for protection
- Turtles = water, Tortoises = land
- Box turtles can close their shells

**Crocodilians**
- Crocodiles (wider snout), Alligators (narrower snout)
- Some of the oldest animals on Earth (existed with dinosaurs)
- Excellent swimmers and ambush predators

### Fun Facts
- Reptiles shed their skin as they grow
- Chameleons change color for communication, not just camouflage
- Some reptiles can survive in very hot deserts and cold mountains
- A Komodo dragon is the largest living lizard (up to 10 feet long!)"""
        },
        {
            "category": "animals/group/amphibians",
            "content": """## Amphibians

Cold-blooded animals that start life in water and grow to live on land.

### Key Characteristics
- Moist, smooth skin (no scales)
- Cold-blooded
- Start life in water (eggs → aquatic babies)
- Most undergo metamorphosis
- Breathe through skin and lungs
- Have a backbone (vertebrates)

### The Life Cycle (Frog Example)
1. **Eggs** — Laid in water, look like jelly balls in clusters
2. **Tadpole** — Hatches from egg, has gills, tail, lives in water
3. **Froglet** — Grows legs, lungs develop, tail shrinks
4. **Adult Frog** — Lives on land, breathes with lungs, eats insects

### Major Types

**Frogs & Toads**
- Frogs: Smooth skin, long legs, jump well
- Toads: Warty skin, walk/hop short distances
- Both eat insects (good for gardens!)

**Salamanders & Newts**
- Look like lizards but have moist skin (not scales)
- Most live near water in damp areas
- Some can regenerate lost limbs

**Caecilians**
- Worm-like amphibians
- Live underground
- Rarely seen

### Fun Facts
- Frogs can see in all directions without moving their heads
- Some frogs freeze solid in winter and thaw out in spring!
- Poison dart frogs have bright colors to warn predators they're toxic
- The word "amphibian" comes from Greek for "double life" (water + land)"""
        },
        {
            "category": "animals/group/fish",
            "content": """## Fish

Cold-blooded animals that live in water, breathe with gills, and have scales.

### Key Characteristics
- Live in water their entire lives
- Breathe with gills (extract oxygen from water)
- Have scales (most of them)
- Cold-blooded
- Have fins for swimming
- Lay eggs in water
- Have a backbone (vertebrates)

### Types of Fish

**Bony Fish** (most fish — about 30,000 species)
- Have skeletons made of bone
- Examples: Goldfish, salmon, tuna, clownfish, seahorses, sharks... wait!
  - Actually sharks are NOT bony fish (see below)
- Have a swim bladder (air sac) that helps them float

**Cartilaginous Fish** (sharks, rays, skates)
- Skeleton made of cartilage (like your ear), not bone
- Sharks have no swim bladder — they must keep swimming to stay up
- Rays and skates are flat and swim near the bottom

**Freshwater Fish** — Live in rivers, lakes, ponds
- Goldfish, trout, catfish, bass, piranha

**Saltwater Fish** — Live in oceans
- Clownfish, tuna, salmon (migrate between fresh and salt), angelfish

### Fun Facts
- The anglerfish uses a light to attract prey in the deep ocean
- Seahorses are fish — the male carries the babies!
- The fastest fish is the sailfish (68 mph)
- The largest fish is the whale shark (40 feet long) — but it only eats plankton
- Fish don't have eyelids — they never blink"""
        },
        {
            "category": "animals/group/insects",
            "content": """## Insects

The most numerous animals on Earth — 6 legs, 3 body parts, and often wings.

### Key Characteristics
- 6 legs (always — this is the #1 way to identify an insect)
- 3 body parts: Head, Thorax, Abdomen
- Most have wings (usually 2 or 4)
- Have an exoskeleton (hard outer covering)
- Antennae on their head
- No backbone (invertebrates)

### Insect Life Cycle (Complete Metamorphosis)
1. **Egg** — Laid by adult female
2. **Larva** — Hatches, eats constantly (caterpillar, grub, maggot)
3. **Pupa** — Transforms inside a case (cocoon, chrysalis)
4. **Adult** — Emerges with wings, can reproduce

### Major Types

**Butterflies & Moths**
- Butterflies: Active during day, bright colors
- Moths: Active at night, usually duller colors
- Caterpillars are butterfly/moth larvae

**Bees, Wasps & Ants**
- Live in colonies with queens
- Bees make honey and pollinate flowers
- Ants are incredible workers — some can carry 50× their body weight

**Beetles**
- Largest group of insects (400,000+ species!)
- Have hard wing covers (elytra)
- Ladybugs, fireflies, June bugs, dung beetles

**Other Insects**
- Grasshoppers & crickets (make sound by rubbing legs)
- Dragonflies (excellent fliers, eat mosquitoes)
- Flies (complete metamorphosis)
- Mosquitoes (females need blood for eggs)

### Fun Facts
- Insects make up about 80% of all animal species
- A butterfly tastes with its feet
- Fireflies make light using chemicals in their bodies (bioluminescence)
- Honey never spoils — archaeologists found edible honey in ancient Egyptian tombs"""
        },
        {
            "category": "animals/group/spiders",
            "content": """## Spiders & Other Arachnids

8-legged creatures — NOT insects (they have 8 legs, not 6).

### Key Characteristics
- 8 legs (insects have 6)
- 2 body parts: Cephalothorax (head + chest fused) and abdomen
- No antennae (insects have them)
- No wings
- Most have 8 eyes
- Make silk (spiders do, others don't)

### Spiders
- Most spiders make webs to catch prey
- Some hunt actively (wolf spiders, jumping spiders)
- All spiders have fangs that inject venom
- Only a few spider species are dangerous to humans (black widow, brown recluse)

### Other Arachnids
- **Scorpions** — Have a stinger on their tail
- **Ticks** — Parasites that feed on blood
- **Mites** — Tiny, many types (dust mites live in your house!)

### Fun Facts
- A spider's silk is stronger than steel (by weight)
- Spiders have 8 eyes but see poorly — they feel vibrations through webs
- Tarantulas can live for 20+ years
- Spiders are beneficial — they control insect populations"""
        },
        {
            "category": "animals/herbivores_carnivores",
            "content": """## What Animals Eat

Animals are classified by what they eat — their diet.

### Herbivores — Plant Eaters
- Eat only plants: grasses, leaves, fruits, seeds, nectar
- Examples: Cows, deer, rabbits, elephants, giraffes, caterpillars
- Often have flat teeth for grinding plants
- Some have special stomachs to digest tough plant fiber

### Carnivores — Meat Eaters
- Eat only meat (other animals)
- Examples: Lions, tigers, wolves, eagles, sharks, frogs
- Have sharp teeth and claws for catching prey
- Sharp canine teeth for tearing meat

### Omnivores — Both Plant and Meat Eaters
- Eat plants AND meat
- Examples: Humans, bears, raccoons, pigs, crows, chickens
- Have both sharp and flat teeth
- Can adapt to different food sources

### Other Diets
- **Insectivores** — Eat only insects (anteaters, bats, woodpeckers)
- **Piscivores** — Eat only fish (otters, herons)
- **Frugivores** — Eat mainly fruit (some bats, monkeys)
- **Detritivores** — Eat decaying matter (earthworms, vultures)

### Food Chains
- Plants make their own food from sunlight (producers)
- Herbivores eat plants (primary consumers)
- Carnivores eat herbivores (secondary consumers)
- Top predators have no natural enemies"""
        },
        {
            "category": "animals/domestic_animals",
            "content": """## Domestic & Farm Animals

Animals that live with or near humans.

### Pets
- **Dogs** — Most popular pet, loyal, many breeds
- **Cats** — Independent, good hunters, come in many breeds
- **Fish** — Goldfish, betta fish, tropical fish
- **Hamsters/Guinea Pigs** — Small mammals, good for kids
- **Birds** — Parakeets, canaries, cockatiels
- **Rabbits** — Herbivores, gentle, need space to hop

### Farm Animals
- **Cows** — Provide milk, beef, leather
- **Chickens** — Provide eggs and meat
- **Pigs** — Raised for meat (pork, bacon, ham)
- **Horses** — Transportation, work, companionship
- **Sheep** — Provide wool and meat
- **Goats** — Provide milk and meat
- **Ducks** — Provide eggs and meat
- **Bees** — Provide honey and pollinate crops

### Working Animals
- **Horses** — Riding, pulling, ranch work
- **Dogs** — Herding, guarding, hunting, service dogs, police dogs
- **Camels** — Transportation in deserts
- **Elephants** — Work in some countries (being phased out for welfare reasons)"""
        },
        {
            "category": "animals/wildlife",
            "content": """## Wild Animals

Animals that live without human care — adapted to survive on their own.

### African Animals
- **Lion** — King of the jungle, lives in prides
- **Elephant** — Largest land animal, very intelligent
- **Giraffe** — Tallest animal, long neck for reaching trees
- **Zebra** — Stripes help confuse predators
- **Cheetah** — Fastest land animal (70 mph)
- **Gorilla** — Closest living relative to humans (besides chimpanzees)

### Asian Animals
- **Tiger** — Largest cat, orange with black stripes
- **Panda** — Eats almost only bamboo
- **Monkey/Chimpanzee** — Closest relatives to humans
- **Elephant** — Asian elephants are smaller than African

### North American Animals
- **Grizzly Bear** — Large bear, omnivore
- **Bald Eagle** — National bird of the USA
- **Wolverine** — Small but fierce
- **Bighorn Sheep** — Live in mountains
- **Gray Wolf** — Lives in packs, hunted in groups

### Ocean Animals
- **Blue Whale** — Largest animal ever
- **Octopus** — 8 arms, very intelligent, can change color
- **Dolphin** — Very smart, lives in pods
- **Shark** — Many species, most are not dangerous to humans
- **Sea Turtle** — Has existed for 200+ million years"""
        },
        {
            "category": "animals/hibernation_migration",
            "content": """## Hibernation & Migration

How animals survive seasonal changes.

### Hibernation — Winter Sleep

**What is it?**
- A deep sleep during winter when food is scarce
- Body temperature drops, heartbeat slows, breathing slows
- Animal lives off stored body fat

**Animals that hibernate:**
- **Bears** — Don't truly hibernate (torpor), but sleep for months
- **Groundhogs** — True hibernators, heartbeat drops dramatically
- **Bats** — Cluster together in caves
- **Salamanders** — Hibernate in mud at bottom of ponds
- **Snakes** — Hibernate in groups in underground burrows

**Summer Sleep (Estivation)**
- Some animals sleep through HOT summer instead
- Desert tortoises, certain frogs, lungfish

### Migration — Seasonal Travel

**What is it?**
- Long-distance travel from one region to another
- Usually to find food, warmth, or breeding grounds

**Animals that migrate:**
- **Monarch Butterflies** — Travel 3,000 miles to Mexico (4 generations complete the round trip!)
- **Arctic Tern** — Flies from Arctic to Antarctica (longest migration)
- **Wildebeest** — Travel 1,000+ miles in Africa following rain
- **Gray Whales** — Swim 5,000+ miles from Arctic to Mexico
- **Canada Geese** — Fly V-formation to warm areas
- **Salmon** — Swim upstream to spawn (return to birthplace)

### Why Animals Do This
- Food runs out in winter (hibernation)
- Weather becomes too cold or dry (migration)
- Need specific conditions to raise young (both)"""
        },
        {
            "category": "animals/endangered",
            "content": """## Endangered & Extinct Animals

Animals at risk of disappearing forever.

### What Does "Endangered" Mean?
- **Endangered** — At high risk of extinction (disappearing forever)
- **Threatened** — Might become endangered soon
- **Extinct** — No more exist anywhere on Earth
- **Extinct in the Wild** — Only exist in zoos or captivity

### Why Animals Become Endangered
- **Habitat loss** — Humans cut down forests, build cities
- **Pollution** — Dirty water, plastic in oceans
- **Climate change** — Changing weather patterns
- **Poaching** — Illegal hunting for profit
- **Invasive species** — Non-native animals outcompete locals

### Famous Endangered Animals
- **Polar Bears** — Ice is melting, less hunting area
- **Giant Pandas** — Bamboo forests being cut down
- **Tigers** — Hunted for fur and body parts
- **Sea Turtles** — Plastic pollution, beach development
- **Whales** — Were hunted nearly to extinction (now recovering)
- **African Elephants** — Poached for ivory tusks

### Extinct Animals
- **Dinosaurs** — Extinct for 65 million years (except birds!)
- **Dodo Bird** — Extinct in 1681, couldn't fly, no predators on its island
- **Passenger Pigeon** — Once billions, extinct in 1914
- **Tasmanian Tiger** — Extinct in 1936
- **Woolly Mammoth** — Extinct about 4,000 years ago

### How We Help
- National parks and wildlife refuges
- Laws against poaching
- Captive breeding programs
- Reducing pollution
- Protecting habitats"""
        },
    ],
}


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

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

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

    print("=== Animals Knowledge Base Ingestion ===")

    # Umbrella
    umbrella_id = ce(
        DATA["umbrella"]["content"],
        DATA["umbrella"]["category"],
        entity_type="animals_umbrella",
        pinned=True,
        strength="strong",
    )
    print(f"  ✅ Umbrella: animals → {umbrella_id[:16]}")

    # Categories
    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]}")

    # Concepts
    for concept in DATA["concepts"]:
        eid = ce(
            concept["content"],
            concept["category"],
        )
        # Link to parent 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} animal entities ingested ===")

    run_queries()


def run_queries():
    queries = [
        "mammals birds reptiles amphibians fish",
        "what is a vertebrate invertebrate",
        "insect life cycle butterfly",
        "animal adaptations camouflage hibernation",
        "difference between frogs and toads",
        "what do carnivores herbivores eat",
        "endangered animals extinction",
        "monarch butterfly migration",
        "spiders vs insects",
        "fish sharks rays",
        "animal hibernation winter",
    ]

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