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

Creates:
- 1 umbrella entity (music)
- 4 categories (elements, instruments, reading_music, music_culture)
- ~12 concept entities

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

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

General knowledge about music: what makes music sound the way it does,
instruments, how to read music, and music in culture.

### Domains
- **Elements of Music:** Pitch, rhythm, tempo, dynamics, melody, harmony
- **Instruments:** The 5 families of orchestra instruments plus percussion
- **Reading Music:** The staff, notes, and basic symbols
- **Music in Culture:** Genres, cultures, and how music connects people

### Key Concepts
- Music has pitch (high/low), rhythm (fast/slow), and dynamics (loud/soft)
- Instruments are grouped into families: strings, woodwinds, brass, percussion, keyboard
- Music is written on a staff using notes
- Different cultures have different musical traditions

**Ingested:** {TODAY}
**Source:** Music knowledge base (general education)
"""
    },

    "categories": [
        {
            "category": "music/elements",
            "type": "music_category",
            "content": """## Elements of Music

The building blocks that make up all music.

### Pitch — How High or Low a Sound Is
- High pitch = squeaky sound (bird chirping, whistle)
- Low pitch = deep sound (thunder, bass guitar)
- Your ears hear pitch all the time — try to identify it!

### Rhythm — The Pattern of Sounds in Time
- Rhythm is the "beat" you tap your foot to
- Some rhythms are steady (marching), some are syncopated (off-beat)
- The **beat** is like a heartbeat — the steady pulse underneath the music

### Tempo — How Fast or Slow the Music Goes
- **Allegro** — Fast and lively
- **Andante** — Walking pace, medium
- **Adagio** — Slow and gentle
- Think: Does this song make you want to run or float?

### Dynamics — How Loud or Soft the Music Is
- **Forte (f)** — Loud
- **Piano (p)** — Soft
- **Crescendo** — Getting louder
- **Decrescendo** — Getting softer

### Melody — The Tune You Hum
- A melody is a series of notes that you can remember
- It's the "tune" — what you'd sing along to
- Every song has a melody

### Harmony — Notes Played Together
- When two or more notes are played at the same time
- Harmony supports the melody
- Chords are groups of notes played together

### Timbre — The "Color" or Character of a Sound
- Why a flute sounds different from a trumpet even at the same pitch
- Each instrument has its own unique sound quality
- Your voice has timbre too — that's why you sound like YOU"""
        },
        {
            "category": "music/instruments",
            "type": "music_category",
            "content": """## Musical Instruments

All the different ways people make music — organized by how they create sound.

### How Instruments Make Sound
- **String** — Vibration of strings (plucked, bowed, or strummed)
- **Woodwind** — Blowing air through a tube (reeds or mouthpiece)
- **Brass** — Blowing air through a mouthpiece and buzzing lips
- **Percussion** — Hitting, shaking, or scraping
- **Keyboard** — Pressing keys that trigger strings or electronics
- **Voice** — The original instrument!

### The 5 Instrument Families

**1. Strings** (bow or pluck)
- Violin, Viola, Cello, Double Bass, Guitar, Harp, Ukulele

**2. Woodwinds** (blow through tube)
- Flute, Clarinet, Oboe, Bassoon, Saxophone

**3. Brass** (buzz lips into mouthpiece)
- Trumpet, Trombone, French Horn, Tuba

**4. Percussion** (hit or shake)
- Drums, Cymbals, Xylophone, Triangle, Maracas, Gong

**5. Keyboards** (press keys)
- Piano, Organ, Harpsichord, Synthesizer

### Fun Facts
- The piano has 88 keys
- The double bass is taller than a person
- The drum is one of the oldest instruments in history
- Some instruments work in more than one family (saxophone is woodwind, not brass)"""
        },
        {
            "category": "music/reading",
            "type": "music_category",
            "content": """## Reading Music

How written music tells musicians what to play.

### The Music Staff
- Five horizontal lines where notes are placed
- Notes higher on the staff = higher pitch
- Notes lower on the staff = lower pitch
- Spaces between lines also hold notes

### The Two Main Clefs

**Treble Clef (𝄞)** — Also called G Clef
- Used for higher-pitched instruments
- Flutes, violins, piano right hand, most singing

**Bass Clef (𝄢)** — Also called F Clef
- Used for lower-pitched instruments
- Cellos, double bass, piano left hand, tuba

### Musical Notes
- There are 7 note names: A, B, C, D, E, F, G — then back to A
- Notes on the staff tell you WHICH note to play
- The shape of the note tells you HOW LONG to hold it

### Note Values
- **Whole note** (𝅝) — Hold for 4 beats
- **Half note** (𝅗𝅥) — Hold for 2 beats
- **Quarter note** (𝅘𝅥) — Hold for 1 beat
- **Eighth note** (𝅘𝅥𝅮) — Hold for half a beat (two make a whole quarter note)

### Time Signature
- Two numbers at the beginning of the staff
- Top number = beats per measure (usually 4, 3, or 2)
- Bottom number = which note gets one beat (usually 4 = quarter note)
- 4/4 time = "common time" — most popular music is in 4/4"""
        },
        {
            "category": "music/culture",
            "type": "music_category",
            "content": """## Music in Culture

Music connects people across time, place, and language.

### Music Genres

**Classical** — Written by composers, played by orchestras
- Bach, Beethoven, Mozart, Tchaikovsky
- Formal, structured, often instrumental

**Jazz** — Improvised, syncopated rhythms
- Started in New Orleans, USA
- Louis Armstrong, Duke Ellington, Miles Davis

**Rock** — Electric guitars, strong beats
- The Beatles, Queen, Rolling Stones

**Pop** — Catchy, radio-friendly
- Designed to be popular and memorable

**Country** — Storytelling songs, acoustic instruments
- Started in rural America, uses guitars, banjo, fiddle

**Hip-Hop/Rap** — Rhythmic speech over beats
- Started in the Bronx, New York
- Often tells stories about life and experiences

**Folk** — Traditional songs passed down orally
- Different in every culture
- Often about daily life, history, and stories

### Music Around the World

**Africa** — Drumming, call-and-response singing, complex rhythms

**Asia** — Many different traditions
- China: Erhu (two-stringed fiddle), guzheng (zither)
- India: Sitar, tabla drums, ragas (melodic frameworks)
- Japan: Shamisen, taiko drums, koto

**Latin America** — Dancing rhythms
- Salsa, samba, tango, bossa nova
- Lots of percussion and colorful melodies

**Middle East** — Microtones, ornamental melodies
- Oud (lute), qanun, darbuka drum

### Music & Emotions
- Fast music → Excitement, energy, happiness
- Slow music → Calm, sadness, reflection
- Major key → Happy, bright feeling
- Minor key → Sad, mysterious feeling
- Music can change your mood instantly!"""
        },
    ],

    "concepts": [
        {
            "category": "music/string_instruments",
            "content": """## String Instruments

Instruments that make sound from vibrating strings.

### How They Work
- Strings are stretched tight over a body
- When you pluck, strum, or bow a string, it vibrates
- The body of the instrument amplifies the vibration
- Thicker strings = lower pitch, thinner strings = higher pitch
- Shorter strings (pressing down) = higher pitch

### The Orchestra String Family

**Violin** — Smallest, highest-pitched
- Held under the chin, played with a bow
- Plays the melody most of the time
- About 14 inches long

**Viola** — Medium size, lower than violin
- Looks like a bigger violin
- Played the same way (under the chin)
- Warm, rich sound

**Cello** — Large, deep sound
- Held between the knees, rests on the floor with an endpin
- Can play both melody and bass lines
- About 4 feet long

**Double Bass** — Largest and lowest
- Almost as tall as a person
- Standing up to play it
- The foundation of the string section

### Other String Instruments
- **Guitar** — Plucked, 6 strings, very popular
- **Ukulele** — Small, 4 strings, Hawaiian
- **Harp** — Many strings, plucked with fingers
- **Banjo** — Round body, bright twangy sound"""
        },
        {
            "category": "music/woodwind_instruments",
            "content": """## Woodwind Instruments

Instruments where you blow air through a tube to make sound.

### How They Work
- Air flows through a tube with holes
- Covering/uncovering holes changes the pitch
- Some use a reed (a thin piece of cane that vibrates)
- Some use just your lips (flute)

### The Woodwind Family

**Flute** — No reed, blow across the mouthpiece
- Silver, shiny, held sideways
- High, clear, singing sound
- One of the oldest instruments

**Clarinet** — Single reed
- Black, cylindrical tube
- Warm, mellow sound
- Can play very low and very high notes

**Oboe** — Double reed
- Pointy, narrow reed
- Bright, piercing sound
- Often plays the "A" that the orchestra tunes to

**Bassoon** — Double reed, largest woodwind
- Long tube folded in half
- Deep, funny-sounding low notes
- About 6 feet long when unfolded

**Saxophone** — Single reed, made of brass (but still a woodwind!)
- Invented by Adolphe Sax in 1840
- Used in jazz, classical, and marching bands
- Comes in sizes: Soprano, Alto, Tenor, Baritone"""
        },
        {
            "category": "music/brass_instruments",
            "content": """## Brass Instruments

Instruments where you buzz your lips into a cup-shaped mouthpiece.

### How They Work
- Your lips vibrate against a mouthpiece
- The metal tube amplifies the buzz into a musical note
- Valves or slides change the length of the tube → change the pitch
- All brass instruments are made of metal (usually brass = copper + zinc)

### The Brass Family

**Trumpet** — Smallest brass, highest-pitched
- 3 valves, held straight
- Bright, heroic sound
- Famous in fanfares and jazz solos

**Trombone** — Uses a slide instead of valves
- Push slide in = higher notes, pull out = lower notes
- Deep, smooth sound
- The only brass instrument that doesn't use valves

**French Horn** — Coiled into a circle with a large bell
- 4 valves, very tricky to play
- Mellow, warm, almost mysterious sound
- Used heavily in orchestras

**Tuba** — Largest brass instrument
- Sits on your lap
- Deepest sound in the orchestra
- The "bass" of the brass section

### Fun Facts
- A trombone slide can extend over 2 feet
- French horn players use both hands on the valves
- Trumpet players can play notes higher than a flute!"""
        },
        {
            "category": "music/percussion_instruments",
            "content": """## Percussion Instruments

The rhythm section — instruments you hit, shake, or scrape.

### How They Work
- Struck with sticks, mallets, hands, or each other
- Shaken (maracas, tambourine)
- Scraped (guiro)
- Percussion keeps the beat and adds color

### Types of Percussion

**Drums**
- **Bass drum** — Large, deep thud
- **Snare drum** — Sharp crack (used in marching bands)
- **Timpani** — Large kettledrums in the orchestra, tunable
- **Drum set** — Combination of drums and cymbals (rock music)

**Mallet Percussion**
- **Xylophone** — Wooden bars, bright sound
- **Glockenspiel** — Metal bars, very high and sparkly
- **Vibraphone** — Metal bars with a motorized vibrato
- **Marimba** — Large wooden bars, warm sound

**Idiophones** (the instrument itself vibrates)
- **Cymbals** — Metal discs, crash or ride
- **Triangle** — Metal bar in a triangle shape, very high ring
- **Gong** — Large metal disc, deep boom
- **Bell** — Metal bell of various sizes
- **Tambourine** — Ring with jingles, held in hand
- **Maracas** — Shaken, from Latin America

### Fun Facts
- Percussion is the oldest type of instrument (drumming goes back thousands of years)
- Some percussion instruments have exact pitches (xylophone, timpani)
- Some are "unpitched" — they add rhythm but no specific note (snare, cymbals)"""
        },
        {
            "category": "music/keyboard_instruments",
            "content": """## Keyboard Instruments

Instruments played with a row of black and white keys.

### The Piano
- 88 keys (52 white, 36 black)
- Hammers strike strings when keys are pressed
- Can play melody and harmony at the same time
- Has a pedal (sustain) that makes notes ring longer
- Invented by Bartolomeo Cristofori in 1700

### Other Keyboards
- **Organ** — Blows air through pipes, used in churches
- **Harpsichord** — Plucks strings, used in classical music (Bach)
- **Synthesizer** — Electronic, can mimic any sound
- **Accordion** — Has a keyboard on one side, squeezed like a bellows

### Piano Basics
- Keys alternate in groups of 2 and 3 black keys
- White keys: A, B, C, D, E, F, G (repeating)
- Middle C is right in the middle of the keyboard
- The further right you go, the higher the pitch"""
        },
        {
            "category": "music/singing_voices",
            "content": """## Singing & Voice Types

The human voice — the most personal musical instrument.

### Voice Types

**Soprano** — Highest female voice
- Light, bright, can sing very high notes
- Often sings the main melody

**Alto** — Lower female voice
- Warm, rich sound
- Provides harmony

**Tenor** — Highest male voice
- Strong, clear
- Often sings the melody in male groups

**Bass** — Lowest male voice
- Deep, rich, powerful
- Provides the foundation

### How We Sing
- Air from lungs passes through vocal cords (strings in your throat)
- Vocal cords vibrate → makes sound
- Your mouth, tongue, and lips shape the sound
- Higher notes = tighter/faster vibrating cords

### Singing Basics
- **Pitch** — Sing the right note
- **Rhythm** — Sing at the right time
- **Breath support** — Use your diaphragm (belly breathing)
- **Diction** — Say the words clearly"""
        },
        {
            "category": "music/dancing",
            "content": """## Dance & Rhythm

How movement and music go together.

### What Is Dance?
- Movement of the body to music
- Can be free (improvised) or choreographed (planned out)
- Every culture has its own dances

### Types of Dance

**Ballet** — Classical, graceful, precise
- Pointe shoes, tutus, bare feet for men
- Very technical — takes years to learn

**Modern/Contemporary** — Free expression, emotional
- No strict rules, barefoot
- Focuses on storytelling through movement

**Hip-Hop** — Street dance, energetic
- Started in the Bronx in the 1970s
- Breakdancing, popping, locking

**Ballroom** — Partner dancing
- Waltz, foxtrot, tango, cha-cha
- Formal and elegant

**Cultural Dances**
- Salsa (Latin America)
- Bhangra (India)
- Traditional Irish step dancing
- African tribal dances

### Rhythm & Counting
- Music is counted in groups (beats)
- Most music counts in groups of 4: "1, 2, 3, 4"
- Waltz is in groups of 3: "1, 2, 3"
- Marching music often in 2 or 4
- Clapping along helps you feel the rhythm"""
        },
    ],
}


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

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

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

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

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


def run_queries():
    queries = [
        "music elements pitch rhythm tempo",
        "string instruments violin cello",
        "woodwind brass instruments",
        "reading music staff notes clef",
        "percussion drums xylophone",
        "music genres jazz classical",
        "music around world cultures",
        "piano keyboard",
        "singing voice types",
        "dance rhythm types",
    ]

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