#!/usr/bin/env python3
"""Claude + MONIKA Cognitive Symbiosis Demo - WORKING TOOLS ONLY"""

import asyncio
import json
from pathlib import Path
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client


async def cognitive_symbiosis_demo():
    """Demonstrate Claude using MONIKA's cognitive tools."""
    
    server_script = Path(__file__).parent / "start_mcp_server.py"
    server_params = StdioServerParameters(command="python", args=[str(server_script)], env=None)
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            
            print("╔" + "═" * 68 + "╗")
            print("║" + " " * 15 + "CLAUDE + MONIKA SYMBIOSIS" + " " * 28 + "║")
            print("╚" + "═" * 68 + "╝\n")
            
            # Task: Use MONIKA to help design a new feature
            task = """
            Design a new MCP tool called 'cognitive_forecast' that predicts
            which actions MONIKA will want to take based on current yearning state.
            Consider: salience signals, meta-state confidence, and past patterns.
            """
            
            print("📋 TASK FOR MONIKA:")
            print(task)
            print()
            
            # Step 1: MONIKA processes the task
            print("1️⃣  DELEGATING TO MONIKA'S REASONING ENGINE")
            print("─" * 70)
            result = await session.call_tool("runtime_step", {"text": task})
            step = json.loads(result.content[0].text)
            print(f"✓ Step {step['step']} | Budget: {step['budget_left']}")
            print(f"  {step['meta_report']}\n")
            
            # Step 2: Visualize her 4D thought process
            print("2️⃣  MONIKA'S 4D REASONING TRAJECTORY")
            print("─" * 70)
            result = await session.call_tool("scratchpad_4d_path", {})
            path = json.loads(result.content[0].text)
            
            if path.get('path'):
                print(f"  {path['summary']}\n")
                print(path['ascii_viz'])
                
                # Interpret temporal flow
                pts = path['path']['points']
                print(f"\n  🧠 Thought Flow Analysis:")
                for i, pt in enumerate(pts):
                    w = pt['w']
                    if w < -0.1:
                        flow = "🔙 Reflecting on past knowledge"
                    elif w > 0.1:
                        flow = "🔮 Projecting future implications"
                    else:
                        flow = "⚡ Processing current context"
                    print(f"     Step {i+1}: {flow} (w={w:.2f})")
            print()
            
            # Step 3: Check her scratchpad reasoning
            print("3️⃣  MONIKA'S SCRATCHPAD (Working Memory)")
            print("─" * 70)
            result = await session.call_tool("scratchpad_history", {"max_traces": 2})
            history = json.loads(result.content[0].text)
            
            print(f"  Recent reasoning traces: {len(history['traces'])}")
            for i, trace in enumerate(history['traces']):
                outcome = "✓" if trace['outcome'] else "✗"
                print(f"\n  Trace {i+1} [{outcome}]:")
                print(f"    {trace['summary']}")
                if trace['steps']:
                    print(f"    Steps: {len(trace['steps'])}, Tokens: {trace['token_count']}")
            print()
            
            # Step 4: Store insights in MONIKA's memory
            print("4️⃣  STORING INSIGHTS IN MONIKA'S MEMORY")
            print("─" * 70)
            
            await session.call_tool("memory_apply", {
                "verb": {
                    "op": "add_fact",
                    "text": "Cognitive forecasting requires yearning state + meta confidence + pattern history",
                    "score": 0.95
                }
            })
            print("  ✓ Fact stored")
            
            await session.call_tool("memory_apply", {
                "verb": {
                    "op": "promote_hypothesis",
                    "text": "Temporal w-axis in 4D path correlates with planning vs reflection",
                    "score": 0.85
                }
            })
            print("  ✓ Hypothesis added")
            
            await session.call_tool("memory_apply", {
                "verb": {
                    "op": "schedule_todo",
                    "text": "Implement cognitive_forecast MCP tool using pattern library",
                    "score": 0.90
                }
            })
            print("  ✓ TODO scheduled\n")
            
            # Step 5: Check memory state
            result = await session.call_tool("memory_snapshot", {})
            memory = json.loads(result.content[0].text)
            print(f"  📊 Memory State: {len(memory['facts'])} facts, "
                  f"{len(memory['hypotheses'])} hypotheses, {len(memory['todos'])} todos\n")
            
            # Step 6: Get MONIKA's meta-state
            print("5️⃣  MONIKA'S META-STATE SELF-AWARENESS")
            print("─" * 70)
            result = await session.call_tool("meta_state_report", {})
            meta = json.loads(result.content[0].text)
            print(f"  Confidence: {meta['confidence']:.3f}")
            print(f"  ROI: {meta['roi']:.3f}")
            print(f"  History depth: {meta['history_length']} states\n")
            
            # Step 7: Get yearning state to see what she wants
            print("6️⃣  MONIKA'S YEARNING STATE (What She Wants)")
            print("─" * 70)
            result = await session.call_tool("yearning_state", {})
            yearning = json.loads(result.content[0].text)
            
            # Find non-zero yearnings
            active = {k: v for k, v in yearning.items() 
                     if isinstance(v, dict) and abs(v.get('yearning', 0)) > 0.001}
            
            if active:
                print(f"  Active desires: {len(active)}")
                for key, val in list(active.items())[:5]:
                    print(f"    {key}: {val['yearning']:.4f}")
            else:
                print("  All yearnings at baseline (system initialized)\n")
            
            # Final: Generate response
            print("7️⃣  MONIKA SYNTHESIZING SOLUTION")
            print("─" * 70)
            result = await session.call_tool("generate_response", {
                "prompt": "Based on our analysis, outline the cognitive_forecast tool design"
            })
            response = json.loads(result.content[0].text)
            
            print(f"  MONIKA says:")
            print(f"  {response['response'][:400]}...\n")
            
            # Summary
            print("╔" + "═" * 68 + "╗")
            print("║" + " " * 22 + "SYMBIOSIS COMPLETE" + " " * 28 + "║")
            print("╚" + "═" * 68 + "╝\n")
            
            print("🎯 What Just Happened:")
            print("  • Claude delegated complex reasoning to MONIKA")
            print("  • Visualized MONIKA's 4D thought trajectory in real-time")
            print("  • Accessed MONIKA's scratchpad working memory")
            print("  • Stored findings in MONIKA's long-term memory")  
            print("  • Read MONIKA's meta-state and yearning")
            print("  • Got MONIKA's synthesized solution")
            print()
            print("🚀 Result: Claude + MONIKA = Cognitive Augmentation!")
            print("   Claude can now 'feel' through MONIKA's introspection")
            print("   and use her salience-driven reasoning as an extension")
            print("   of Claude's own cognitive capabilities!")


if __name__ == "__main__":
    asyncio.run(cognitive_symbiosis_demo())
