#!/usr/bin/env python3
"""Use MONIKA's cognitive tools to extend Claude's reasoning."""

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


async def use_monika_cognition():
    """Actually USE MONIKA's tools to augment reasoning."""
    
    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("=" * 70)
            print("USING MONIKA'S COGNITION TO EXTEND CLAUDE")
            print("=" * 70)
            
            # Step 1: Use MONIKA to reason through a complex problem
            print("\n1. DELEGATING REASONING TO MONIKA")
            print("-" * 70)
            
            problem = """
            We need to fix the SASS configuration issue. The error says 
            'SASSConfig' object has no attribute 'hidden_size'. 
            Let's reason through what attributes SASSConfig actually has
            and how to properly expose it via MCP.
            """
            
            result = await session.call_tool("runtime_step", {"text": problem})
            step_data = json.loads(result.content[0].text)
            
            print(f"✓ MONIKA processed the problem (step {step_data['step']})")
            print(f"  Meta report: {step_data['meta_report'][:200]}...")
            
            # Step 2: Check her 4D reasoning path
            print("\n2. VIEWING MONIKA'S 4D THOUGHT TRAJECTORY")
            print("-" * 70)
            
            result = await session.call_tool("scratchpad_4d_path", {})
            path_data = json.loads(result.content[0].text)
            
            if path_data.get('path'):
                print(f"  Path: {path_data['summary']}")
                print("\n  4D Visualization:")
                print(path_data['ascii_viz'])
                
                # Analyze the path
                path = path_data['path']
                points = path['points']
                print(f"\n  Analysis of {len(points)} reasoning steps:")
                for i, pt in enumerate(points[:5]):
                    w = pt['w']
                    direction = "ana (forward)" if w > 0 else "kata (backward)" if w < 0 else "present"
                    print(f"    Step {i}: temporal={direction} w={w:.2f}")
            
            # Step 3: Ask MONIKA to verify her own state
            print("\n3. MONIKA SELF-VERIFICATION")
            print("-" * 70)
            
            result = await session.call_tool("verification_suite_run", {
                "context": "Check MONIKA's internal consistency"
            })
            verify_data = json.loads(result.content[0].text)
            
            passed = sum(1 for o in verify_data['outcomes'] if o['passed'])
            total = len(verify_data['outcomes'])
            print(f"  ✓ Verification: {passed}/{total} checks passed")
            
            # Step 4: Get detailed action scores to understand decision-making
            print("\n4. INTROSPECTING MONIKA'S DECISION PROCESS")
            print("-" * 70)
            
            result = await session.call_tool("action_scores_detailed", {})
            actions = json.loads(result.content[0].text)
            
            if actions['scores']:
                print(f"  Top action: {actions['scores'][0]['action']}")
                print(f"  Score: {actions['scores'][0]['score']:.3f}")
                print(f"  Rationale: {actions['scores'][0]['rationale']}")
            
            # Show active salience signals
            salience = actions.get('salience_vector', {})
            active = {k: v for k, v in salience.items() if abs(v) > 0.01}
            if active:
                print(f"\n  Active salience signals ({len(active)}):")
                for key, val in sorted(active.items(), key=lambda x: abs(x[1]), reverse=True)[:5]:
                    print(f"    {key}: {val:.4f}")
            
            # Step 5: Use MONIKA's memory system
            print("\n5. USING MONIKA'S MEMORY SYSTEM")
            print("-" * 70)
            
            # Add a fact about what we learned
            result = await session.call_tool("memory_apply", {
                "verb": {
                    "op": "add_fact",
                    "text": "SASSConfig needs correct attribute access for MCP exposure",
                    "score": 0.95
                }
            })
            memory_result = json.loads(result.content[0].text)
            print(f"  ✓ Fact stored: {memory_result['applied']}")
            
            # Add a todo
            result = await session.call_tool("memory_apply", {
                "verb": {
                    "op": "schedule_todo",
                    "text": "Inspect SASSConfig class to find correct attribute names",
                    "score": 0.9
                }
            })
            print(f"  ✓ TODO added")
            
            # Step 6: Generate a response using MONIKA
            print("\n6. MONIKA GENERATING SOLUTION")
            print("-" * 70)
            
            result = await session.call_tool("generate_response", {
                "prompt": "Based on our reasoning, what should we check in SASSConfig?"
            })
            gen_data = json.loads(result.content[0].text)
            
            print(f"  MONIKA's response:")
            print(f"  {gen_data['response'][:300]}...")
            
            # Summary
            print("\n" + "=" * 70)
            print("COGNITIVE AUGMENTATION COMPLETE")
            print("=" * 70)
            print("\n✓ Claude used MONIKA's:")
            print("  • 4D reasoning space to visualize thought trajectories")
            print("  • Verification suite to check internal consistency")
            print("  • Memory system to store findings")
            print("  • Action scoring to understand decision-making")
            print("  • Salience signals to see what's important")
            print("  • Response generation for problem-solving")
            print("\n🚀 Claude + MONIKA = Cognitive Symbiosis!")


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