#!/usr/bin/env python3
"""Ignite MONIKA by feeding her through her own cognitive systems."""

import sys
sys.path.insert(0, 'C:\\MONIKA')

# Use MCP server directly
from salience_os_seed.runtime.mcp_server import MCPServer
from pathlib import Path
import asyncio

async def ignite():
    # Server already has session loaded
    print("=== Igniting MONIKA's Cognitive Loop ===\n")
    
    # Load Alice in Wonderland
    corpus = Path("C:\\MONIKA\\datasets\\alice_wonderland.txt").read_text(encoding='utf-8', errors='ignore')
    
    # Clean
    if "*** START" in corpus:
        corpus = corpus.split("*** START", 1)[1]
    if "*** END" in corpus:
        corpus = corpus.split("*** END", 1)[0]
    
    # Split into sentences
    import re
    sentences = re.split(r'[.!?]+\s+', corpus)
    sentences = [s.strip() for s in sentences if 20 < len(s.strip()) < 200]
    
    print(f"Loaded {len(sentences)} sentences from Alice in Wonderland")
    print("Feeding through cognitive loop...\n")
    
    # Feed through runtime_step (full cognitive engagement)
    for i, sentence in enumerate(sentences[:200]):  # First 200 sentences
        try:
            # This engages: Controller → SASS → Memory → Reflection → Learning
            result = server.session.process_user_input(sentence)
            
            if (i + 1) % 20 == 0:
                step = server.proto_lm.step
                vocab = server.proto_lm.vocab.size()
                loss = getattr(server.proto_lm, '_latest_loss', 0)
                print(f"  [{i+1}/200] step={step}, vocab={vocab}, loss={loss:.2f}")
                print(f"    yearning_desire={result.yearning_snapshot.get('depth=0|op=SASS|patch=NONE', {}).get('desire', 0):.3f}")
        except Exception as e:
            print(f"  Error at {i}: {e}")
            continue
    
    print(f"\nFinal state:")
    print(f"  Step: {server.proto_lm.step}")
    print(f"  Vocab: {server.proto_lm.vocab.size()}")
    print(f"  Memory facts: {len(server.session.runtime.memory._facts)}")
    
    # Test generation through cognitive system
    print("\n=== Testing Cognitive Generation ===")
    snapshot = server.session.generate_response("Hello, I am learning")
    print(f"Response: {snapshot.response[:150]}")
    
    # Save
    checkpoint = server.proto_lm.save_checkpoint(
        reason="cognitive-loop-ignited",
        tags=["runtime-trained", "full-system-engaged"]
    )
    print(f"\nSaved: {checkpoint}")

# Can't run async from here easily, so write synchronous version
if __name__ == "__main__":
    print("ERROR: Need to call through MCP runtime_step tool")
    print("Use fastfood on sentences instead, or converse_with_monika")
