#!/usr/bin/env python3
"""
Deep Phonics & Reading Comprehension Knowledge Base Ingestion

Ingests into brain:
  1. Individual vowel sound teaching rules (per-vowel, with examples/tricks)
  2. Reading comprehension activity structures (patterns, question types)
  3. Grammar progression across 18 weeks
  4. Worksheet activity type patterns
"""
import sys
sys.path.insert(0, '/home/vincent/.hermes/brain')
from brain import create_entity, add_edge, get_entity, list_entities

def e(text):
    """Safe entity content helper."""
    return text

def add(pattern_id, content, pinned=False, strength='strong', category='phonics', entity_type='phonics/pattern'):
    existing = get_entity(pattern_id)
    if existing:
        print(f"  SKIP {pattern_id} (exists)")
        return False
    create_entity(
        content=content,
        entity_id=pattern_id,
        entity_type=entity_type,
        category=category,
        strength=strength,
        pinned=pinned,
        log=True
    )
    print(f"  ✓ {pattern_id}")
    return True

def edge(a, relation, b):
    add_edge(a, relation, b, 0.8)

# ===========================================================================
# 1. INDIVIDUAL VOWEL SOUND RULES (deep teaching rules per vowel)
# ===========================================================================
print("\n=== 1. Individual Vowel Sound Teaching Rules ===")

# Short vowels - individual
add("vowel_short_a",
    "Short A — /ă/ as in 'at', 'cat', 'hat'. The vowel makes its quickest, flattest sound. "
    "Teaching trick: 'Short a says /a/ like in apple!' "
    "Examples: at, bag, fan, hat, jam, log, man, pan, rat, sat, tag, van.")

add("vowel_short_e",
    "Short E — /ĕ/ as in 'eggs', 'fence'. Teaching trick: 'Short e says /e/ like in eggs!' "
    "Examples: bed, bell, end, fern, fence, gem, hen, jet, leg, met, pen, ten.")

add("vowel_short_i",
    "Short I — /ĭ/ as in 'ink', 'pint'. Teaching trick: 'Short i says /i/ like in igan (like Michigan)!' "
    "Examples: big, bit, dip, fit, gin, hip, ink, kin, lip, mix, pin, rim.")

add("vowel_short_o",
    "Short O — /ŏ/ as in 'on', 'pots'. Teaching trick: 'Short o says /o/ like in octopus!' "
    "Examples: cod, cod, fog, hop, hot, job, log, mud, not, pot, rod, sod.")

add("vowel_short_u",
    "Short U — /ŭ/ as in 'up', 'cups'. Teaching trick: 'Short u says /u/ like in umbrella!' "
    "Examples: bud, bug, bun, cup, cut, dug, fun, gum, hut, jug, mug, nut, pup, rut, sun.")

# Link short vowels to parent
for v in ["a", "e", "i", "o", "u"]:
    edge(f"vowel_short_{v}", "is_a", "phonics_short_vowels")

# Silent E rules per vowel
add("vowel_silent_e_long_a",
    "Silent E makes short A say its name: /ā/. Pattern: CVCe. "
    "Examples: create, strange, cave, plate, mate, rate, safe, wave. "
    "Teaching trick: 'The e is silent but it tells the vowel to say its name!'" )

add("vowel_silent_e_long_e",
    "Silent E makes short E say its name: /ē/. Pattern: CVCe. "
    "Examples: behave, relieve, piece, these. "
    "Teaching trick: 'E says its name when a silent e visits!'")

add("vowel_silent_e_long_i",
    "Silent E makes short I say its name: /ī/. Pattern: CVCe. "
    "Examples: invite, divide, polite, noise, voice. "
    "Teaching trick: 'I says its name when a silent e visits!'")

add("vowel_silent_e_long_o",
    "Silent E makes short O say its name: /ō/. Pattern: CVCe. "
    "Examples: remote, devote, remote, devote, remote. "
    "Teaching trick: 'O says its name when a silent e visits!'")

add("vowel_silent_e_long_u",
    "Silent E makes short U say its name: /ū/. Pattern: CVCe. "
    "Examples: rescue, behave. "
    "Teaching trick: 'U says its name when a silent e visits!'")

for v in ["long_a", "long_e", "long_i", "long_o", "long_u"]:
    edge(f"vowel_silent_e_{v}", "is_a", "phonics_silent_e")

# Vowel teams - individual
add("vowel_team_ai",
    "Vowel Team AI — makes long A /ā/ sound. Usually in the middle of words. "
    "Examples: rail, train, rain, rain, railroad, rainbow, train, wait, paint. "
    "Rule: 'AI says long A and usually stays in the middle of words.'")

add("vowel_team_ay",
    "Vowel Team AY — makes long A /ā/ sound. Usually at the end of words. "
    "Examples: day, play, spray, clay, tray, gray, stay, way. "
    "Rule: 'AY says long A and usually sits at the end of words.'")

add("vowel_team_ee",
    "Vowel Team EE — makes long E /ē/ sound. "
    "Examples: tree, free, bee, tree, free, see, bee, tree, freeze, green, sweep. "
    "Rule: 'EE says long E — two e's together make one long e sound.'")

add("vowel_team_ea",
    "Vowel Team EA — makes long E /ē/ sound (same as EE). "
    "Examples: eat, team, tea, meal, read, beach, teacher, each, peace. "
    "Rule: 'EA says long E — just like EE!'")

add("vowel_team_oa",
    "Vowel Team OA — makes long O /ō/ sound. "
    "Examples: boat, coat, load, road, toadstool, sailboat, goat, float, toast. "
    "Rule: 'OA says long O — like in boat and road.'")

add("vowel_team_ow_long",
    "Vowel Team OW — can make long O /ō/ (like 'snow') OR owl /ow/ sound (like 'cow'). "
    "Long O examples: snow, slow, grow, snowball, glow. "
    "Owl sound examples: cow, how, now, town, brown, flower, shout. "
    "Rule: 'OW can say long O or the owl sound — context tells you which!'")

add("vowel_team_ou",
    "Vowel Team OU — makes an ou/ow sound. "
    "Examples: out, found, loud, shout, cloud, around, mouth, house, south. "
    "Rule: 'OU makes a sound that starts with o and ends with u — ou!'")

add("vowel_team_ew",
    "Vowel Team EW — can make long U /oo/ sound (like 'new') OR /oh/ sound (like 'chew'). "
    "Long U examples: new, few, flew, blew, grew, stew. "
    "Oh sound examples: chew, blew, sew, threw. "
    "Rule: 'EW usually says /oo/ like in new!'")

# Link vowel teams
for vt in ["ai", "ay", "ee", "ea", "oa", "ow_long", "ou", "ew"]:
    edge(f"vowel_team_{vt}", "is_a", "phonics_vowel_teams")

# Digraphs - individual
add("digraph_sh",
    "Digraph SH — two letters, one sound: /sh/. The quieting sound — 'shhh!' "
    "Examples: ship, shoe, shine, shell, sheep, shed, fish, dish, push, wish, shelter, wish, brush. "
    "Rule: 'SH says /sh/ — two letters, one sound! Put a finger to your lips — shhh!'")

add("digraph_ch",
    "Digraph CH — two letters, one sound: /ch/. "
    "Examples: chip, chin, chef, chef, chat, chop, chef, chef, chef, chef. "
    "Examples: chef, chef, chef, chef, chef. "
    "Rule: 'CH says /ch/ — like a train: ch-ch-ch-ch!'")

add("digraph_th",
    "Digraph TH — two letters, one sound: /th/. Put your tongue between your teeth! "
    "Examples: the, this, that, them, they, them, them, them. "
    "Voiceless (thin, thigh): /th/ without voice. Voiced (the, this): /th/ with voice. "
    "Rule: 'TH says /th/ — tongue between teeth!'")

add("digraph_wh",
    "Digraph WH — two letters, one sound: /hw/. A breathy h followed by w. "
    "Examples: what, when, where, why, who, whale, wheel, white, whale, whale. "
    "Rule: 'WH says /hw/ — a whistling h sound!'")

add("digraph_ph",
    "Digraph PH — two letters, makes the /f/ sound. Greek origin. "
    "Examples: phone, photo, ship, phone, dolphin, elephant, physics, phone, phone. "
    "Rule: 'PH says /f/ — a Greek letter pair that sounds like f!'")

add("digraph_ck",
    "Digraph CK — two letters, makes the /k/ sound. Usually after a short vowel at the end of words or syllables. "
    "Examples: kick, sick, rock, duck, neck, sock, back, pack, check, click, lock, black. "
    "Rule: 'CK says /k/ — after a short vowel, at the end of a word!'")

for dg in ["sh", "ch", "th", "wh", "ph", "ck"]:
    edge(f"digraph_{dg}", "is_a", "phonics_digraphs")

# R-controlled vowels - individual
add("r_controlled_ar",
    "R-Controlled AR — /ar/ sound. The r changes the a sound completely. "
    "Examples: market, farmer, car, jar, star, bark, dark, park, farm, arm, hart, tart. "
    "Rule: 'AR says /ar/ — like saying ar at the doctor!'")

add("r_controlled_er",
    "R-Controlled ER — /er/ sound. The r changes the e sound. "
    "Examples: silver, winter, better, feather, her, fern, term, germ, herd, term, worm. "
    "Rule: 'ER says /er/ — a squishy middle sound!'")

add("r_controlled_ir",
    "R-Controlled IR — /er/ sound. Same as ER! The r changes the i sound to the same squishy /er/. "
    "Examples: mirror, stir, girl, bird, first, third, shirt, skirt, dirt, hurt, swirl, twirl. "
    "Rule: 'IR says /er/ — same sound as ER!'")

add("r_controlled_or",
    "R-Controlled OR — /or/ sound. The r changes the o sound. "
    "Examples: doctor, corner, fort, sort, sport, horse, storm, horn, born, torn, worn, fork. "
    "Rule: 'OR says /or/ — like a horse saying or!'")

add("r_controlled_ur",
    "R-Controlled UR — /er/ sound. Same as ER and IR! The r changes the u sound to the same squishy /er/. "
    "Examples: purple, turtle, fur, hurt, turn, burn, nurse, purse, curl, swirl, purr, churn. "
    "Rule: 'UR says /er/ — same sound as ER and IR! Three patterns, one sound!'")

for rc in ["ar", "er", "ir", "or", "ur"]:
    edge(f"r_controlled_{rc}", "is_a", "phonics_r_controlled")

# Soft C/G rules
add("soft_c_rule",
    "Soft C Rule — C makes /s/ sound (instead of /k/) when followed by E, I, or Y. "
    "Examples: circle (/s/), notice (/s/), decide (/s/), city, cycle, face, ice, fancy, voice, cycle. "
    "Hard C = /k/: cat, can, coat, cut, clock, crack, back. "
    "Rule: 'C is soft (says /s/) before E, I, Y. C is hard (says /k/) before A, O, U.' "
    "Mnemonic: 'C is soft before E, I, Y — all the other times, C says /k/!'")

add("soft_g_rule",
    "Soft G Rule — G makes /j/ sound (instead of /g/) when followed by E, I, or Y. "
    "Examples: gentle (/j/), finger (/j/), danger (/j/), gem, giant, gym, huge, age, large, change. "
    "Hard G = /g/: go, got, gun, dog, bag, log, leg, big. "
    "Rule: 'G is soft (says /j/) before E, I, Y. G is hard (says /g/) before A, O, U.' "
    "Note: More exceptions than soft C — game, guest are hard G before E." )

edge("soft_c_rule", "is_a", "phonics_soft_cg")
edge("soft_g_rule", "is_a", "phonics_soft_cg")

# Double consonant rules
add("double_consonant_t",
    "Double T (TT) — makes the vowel before it SHORT. "
    "Examples: butter, bitter, cotton, kitten, butter, better, lettuce, mattress, puddle. "
    "Rule: 'TT keeps the vowel short and snappy!'")

add("double_consonant_p",
    "Double P (PP) — makes the vowel before it SHORT. "
    "Examples: hopper, apple, happen, pepper, supper, puppy, happy, hippo, puppet. "
    "Rule: 'PP keeps the vowel short and snappy!'")

add("double_consonant_z",
    "Double Z (ZZ) — makes the vowel before it SHORT. "
    "Examples: puzzle, dizzy, buzz, jazz, fuzz, fizz, buzz, dazzle, puzzle, sizzle. "
    "Rule: 'ZZ keeps the vowel short and snappy!'")

add("double_consonant_m",
    "Double M (MM) — makes the vowel before it SHORT. "
    "Examples: hammer, hammer, hammer, summer, hammer, hammer. "
    "Examples: hammer, summer, hammer, hammer, hammer. "
    "Rule: 'MM keeps the vowel short and snappy!'")

add("double_consonant_n",
    "Double N (NN) — makes the vowel before it SHORT. "
    "Examples: bunny, bunny, bunny, bunny, bunny, funny, bunny, sunny, bunny, bunny. "
    "Rule: 'NN keeps the vowel short and snappy!'")

add("double_consonant_d",
    "Double D (DD) — makes the vowel before it SHORT. "
    "Examples: add, added, adding, middle, ladder, puddle, paddle, odd, ladder, middle. "
    "Rule: 'DD keeps the vowel short and snappy!'")

add("double_consonant_g",
    "Double G (GG) — makes the vowel before it SHORT. "
    "Examples: egg, egg, egg, egg, egg, egg, egg, egg, egg. "
    "Rule: 'GG keeps the vowel short and snappy!'")

for dc in ["t", "p", "z", "m", "n", "d", "g"]:
    edge(f"double_consonant_{dc}", "is_a", "phonics_double_consonants")

# ===========================================================================
# 2. READING COMPREHENSION ACTIVITY STRUCTURES
# ===========================================================================
print("\n=== 2. Reading Comprehension Activity Structures ===")

add("readcomp_literal_questions",
    "Literal Comprehension Questions — ask about explicit facts stated directly in the text. "
    "Format: 'What/Where/Who/When' questions with answers found verbatim in the passage. "
    "Examples: 'What did they build near the fountain?', 'Where did they see a sailboat?', "
    "'What was in the first exhibit at the museum?' "
    "Purpose: Verify the student actually read and understood the basic facts. "
    "Pattern: 3 questions per passage, each targeting a different sentence or fact.",
    category='reading', entity_type='reading/activity')

add("readcomp_inference_questions",
    "Inference Comprehension Questions — require the student to read between the lines. "
    "The answer is implied but not directly stated. "
    "Examples: 'How does the character feel?', 'Why did they do that?', 'What will happen next?' "
    "Purpose: Develop higher-order thinking — students must combine text clues with prior knowledge.",
    category='reading', entity_type='reading/activity')

add("readcomp_paragraph_builder",
    "Paragraph Builder Activity — guided writing using sentence starters. "
    "Structure: Topic sentence starter → Detail sentence starters → Closing sentence starter. "
    "Remember This! rule: Topic sentence, details, closing sentence. "
    "Example prompts: 'The circus was exciting because ___', 'My favorite part was ___', "
    "'I will never forget ___'. "
    "Purpose: Teach paragraph structure — the foundation of organized writing.",
    category='reading', entity_type='reading/activity')

add("readcomp_word_swap",
    "Word Swap Challenge — replace bold words in sentences with new vocabulary words. "
    "Structure: Original sentence with 2 bold words → student replaces each with a new word "
    "and writes a fresh sentence. "
    "Example: 'The [kitten] slept in the [basket].' → replace with 'animal' and 'garden'. "
    "Purpose: Build flexible sentence construction and vocabulary transfer.",
    category='reading', entity_type='reading/activity')

add("readcomp_spelling_map",
    "Spelling Map Activity — chart that connects words to their vowel patterns. "
    "Structure: Table with columns: Word | Vowel Pattern | What It Means. "
    "First 2 rows filled in as examples, student completes the rest. "
    "Purpose: Metacognitive awareness — students identify the phonics pattern in each word.",
    category='reading', entity_type='reading/activity')

add("readcomp_word_detective",
    "Word Detective Activity — find and fix intentionally misspelled words. "
    "Structure: List of words with one letter wrong (missing, swapped, or extra). "
    "Example: 'resc' → 'rescue', 'invote' → 'invite', 'behav' → 'behave'. "
    "Purpose: Develop spelling awareness and self-correction skills.",
    category='reading', entity_type='reading/activity')

add("readcomp_story_writing",
    "Story Writing Activity — free creative writing using weekly vocabulary. "
    "Structure: 'Write a creative story using at least 5 spelling words from this week. "
    "Use complete sentences with capital letters and periods!' "
    "Format: Blue sky-fence-ground writing lines for handwriting practice. "
    "Purpose: Synthesize the week's vocabulary into connected, creative writing.",
    category='reading', entity_type='reading/activity')

add("readcomp_pattern_hunt",
    "Pattern Hunt / Vowel Hunt Activity — check or circle the target vowel pattern in words. "
    "Structure: Words displayed with checkboxes. Target vowel letter highlighted in color (#FF7043). "
    "Words shown in colored boxes with check boxes. "
    "Purpose: Visual pattern recognition — train the eye to spot the phonics pattern.",
    category='reading', entity_type='reading/activity')

add("readcomp_builder_prompts",
    "Builder Prompts — guided sentence writing with target vocabulary. "
    "Structure: Prompt sentence → target word student must include. "
    "Example: 'Write a sentence about an escape.' (target: 'escape'). "
    "Purpose: Scaffolded writing practice with vocabulary application.",
    category='reading', entity_type='reading/activity')

# Link reading comp activities to parent
for rc in ["literal_questions", "inference_questions", "paragraph_builder", "word_swap",
           "spelling_map", "word_detective", "story_writing", "pattern_hunt", "builder_prompts"]:
    edge(f"readcomp_{rc}", "is_a", "reading_comprehension")

# Create umbrella reading comprehension entity
rc_exists = get_entity("reading_comprehension")
if not rc_exists:
    add("reading_comprehension",
        "Reading Comprehension — collection of literacy activity structures used across all 18 weeks "
        "of 2nd grade ELA. Each week includes a reading passage with bold target vocabulary words, "
        "followed by comprehension questions and writing activities.",
        pinned=True, category='reading', entity_type='reading/domain')

# ===========================================================================
# 3. GRAMMAR PROGRESSION (across 18 weeks)
# ===========================================================================
print("\n=== 3. Grammar Progression Across 18 Weeks ===")

grammar_weeks = [
    (1, "sentences", "Sentences — complete thoughts starting with capital letter, ending with punctuation. "
     "Period (.), question mark (?), exclamation point (!)."),
    (2, "sentences_deep", "Sentences (deep) — capital letters, punctuation types, sentence vs fragment."),
    (3, "verbs", "Verbs — action words that tell what someone or something is doing. "
     "Examples: runs, eats, reads, jump, climbed."),
    (4, "past_tense", "Past Tense (-ed) — adding -ed to verbs to show the action is finished. "
     "Present: I run → Past: I jumped. Present: I climb → Past: I climbed."),
    (5, "punctuation_questions", "Question Marks & Exclamation Points — question marks (?) end questions, "
     "exclamation points (!) show excitement or strong feelings."),
    (6, "adjectives", "Adjectives — describing words that tell us more about nouns. "
     "Examples: gentle breeze, circular path, high ceiling."),
    (7, "adverbs", "Adverbs (-ly) — tell us HOW something happens. Most end in -ly. "
     "Describe verbs, not nouns. Examples: moved slowly, worked quickly."),
    (8, "compound_sentences", "Compound Sentences — join two complete ideas with comma + FANBOYS. "
     "FANBOYS = For, And, Nor, But, Or, Yet, So. "
     "Pattern: Complete sentence + , FANBOYS + Complete sentence."),
    (9, "prefixes", "Prefixes — word parts added to the beginning that change meaning. "
     "UN- = not, RE- = again, DIS- = not/opposite."),
    (10, "suffixes_tense", "Suffixes for Tense/Plural — -ed (past tense), -ing (present progressive), "
     "-s/-es (plural nouns, 3rd person singular verbs)."),
    (11, "suffixes_comparative", "Suffixes for Comparison/Degree — -er (comparative), -est (superlative), "
     "-ly (adverb), -ful (full of), -less (without)."),
    (12, "none", None),  # homophones week, no grammar focus
    (13, "none", None),  # sight words week
    (14, "synonyms", "Synonyms — words with the same or very similar meanings. "
     "Using synonyms makes writing more interesting and precise."),
    (15, "antonyms", "Antonyms — words with opposite meanings. "
     "Contrasting sentences with 'but', 'yet', 'although'."),
    (16, "capitalization", "Capitalization Rules — capitalize first word of sentences, proper nouns, "
     "pronoun 'I', days of week, months, titles."),
    (17, "word_families", "Word Families — groups of words sharing the same root/base word. "
     "Add prefixes/suffixes to create family members. "
     "Example: help → helper, helpful, helpless."),
    (18, "suffixes_advanced", "Advanced Suffixes — -ious (ee-uhs), -ous (uhs), -ful (full of), "
     "-ible (able to be), -ile (ih-ul)."),
]

# Create grammar progression umbrella
add("grammar_progression",
    "Grammar Progression — 18-week sequence of grammar concepts in 2nd grade ELA. "
    "Progression: Sentences → Verbs → Past Tense → Punctuation → Adjectives → Adverbs → "
    "Compound Sentences → Prefixes → Suffixes (tense/plural) → Suffixes (comparison) → "
    "Synonyms → Antonyms → Capitalization → Word Families → Advanced Suffixes. "
    "Each week's grammar builds on previous weeks.",
    pinned=True, category='grammar', entity_type='grammar/curriculum')

for week, gid, content in grammar_weeks:
    if content:
        add(f"grammar_w{week:02d}_{gid}", content, category='grammar', entity_type='grammar/concept')
        edge(f"grammar_w{week:02d}_{gid}", "is_a", "grammar_progression")

# Link sequential grammar concepts
grammar_ids = [f"grammar_w{w:02d}_{g}" for w, g, c in grammar_weeks if c]
for i in range(len(grammar_ids) - 1):
    # We'll use "comes_before" but the brain API uses "precedes"
    add_edge(grammar_ids[i], "precedes", grammar_ids[i+1], 0.9)

# ===========================================================================
# 4. WORKSHEET ACTIVITY TYPE PATTERNS
# ===========================================================================
print("\n=== 4. Worksheet Activity Type Patterns ===")

add("activity_vowel_sort",
    "Vowel Sort Activity — sort words into categories by their vowel pattern. "
    "Structure: Category labels across the top (e.g., 'ai', 'ay', 'ee', 'ea'), "
    "student places words under the correct label. "
    "Format: Table or column layout. "
    "Purpose: Categorization practice — train pattern recognition and classification.",
    category='activity', entity_type='activity/type')

add("activity_remember_this",
    "Remember This! Box — teaching rule summary in a highlighted box. "
    "Structure: Colored box with rule statement and examples. Appears on each worksheet. "
    "Purpose: Quick reference — students can look back at the rule while completing activities.",
    category='activity', entity_type='activity/type')

add("activity_writing_lines",
    "Writing Lines — blue sky-fence-ground handwriting practice lines. "
    "Structure: Three horizontal lines — sky line (top, dashed), fence line (middle, dashed), "
    "ground line (bottom, solid). Letters sit on the ground with ascenders reaching the sky. "
    "Purpose: Proper letter formation and handwriting development.",
    category='activity', entity_type='activity/type')

# Link activities to reading comprehension
for act in ["vowel_sort", "remember_this", "writing_lines"]:
    edge(f"activity_{act}", "used_in", "reading_comprehension")

# ===========================================================================
# 5. CROSS-LINK: CONNECT DEEP RULES TO EXISTING PARENT ENTITIES
# ===========================================================================
print("\n=== 5. Cross-links ===")

# Connect grammar to curriculum
add_edge("grammar_progression", "part_of", "domain_curriculum", 0.9)
add_edge("reading_comprehension", "part_of", "domain_curriculum", 0.9)

# Connect reading comp to phonics patterns (reading uses phonics)
add_edge("reading_comprehension", "builds_on", "phonics_progression", 0.7)

# Connect activity types to parent
for act in ["vowel_sort", "remember_this", "writing_lines"]:
    edge(f"activity_{act}", "part_of", "reading_comprehension")

print("\n=== DONE ===")
print("Check entity counts below...")
