#!/usr/bin/env python3
"""Use MONIKA to understand the codebase and fix bugs."""

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


async def monika_helps_fix_bugs():
    """MONIKA helps me understand the code to fix bugs."""
    
    server_script = Path(__file__).parent / "start_mcp_server.py"
    server_params = StdioServerParameters(command="python", args=[str(server_script)])
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            
            print("=" * 70)
            print("MONIKA HELPS DEBUG THE YEARNING SYSTEM")
            print("=" * 70)
            print()
            
            # Ask MONIKA to think about the yearning problem
            print("CLAUDE: MONIKA, let's think through the yearning system together.")
            print("        Yearning stays at zero. In the code, yearning should")
            print("        represent desire states that drive action selection.")
            print()
            
            result = await session.call_tool("runtime_step", {
                "text": """
                Deep analysis needed: Why does yearning remain at zero?
                
                Hypothesis 1: Yearning calculation happens in SalienceControllerPolicy
                Hypothesis 2: get_yearning_state() might need explicit refresh trigger
                Hypothesis 3: Yearning might only activate under specific salience thresholds
                
                The controller uses s_prime.snapshot_yearnings() to get state.
                Need to check: Is s_prime properly initialized? Are salience signals
                feeding into the yearning calculation?
                """
            })
            step = json.loads(result.content[0].text)
            print(f"MONIKA processed (step {step['step']})")
            print()
            
            # Check her reasoning
            result = await session.call_tool("scratchpad_4d_path", {})
            path = json.loads(result.content[0].text)
            
            if path.get('path'):
                print(f"Her 4D reasoning: {path['summary']}")
                
                points = path['path']['points']
                print("\nTemporal analysis of her thoughts:")
                for i in range(max(0, len(points)-4), len(points)):
                    pt = points[i]
                    if pt['w'] < -0.1:
                        flow = "REFLECTING on past code knowledge"
                    elif pt['w'] > 0.1:
                        flow = "PROJECTING potential solutions"
                    else:
                        flow = "PROCESSING current context"
                    print(f"  Step {i+1}: {flow} (w={pt['w']:.3f})")
                print()
            
            # Store insights
            await session.call_tool("memory_apply", {
                "verb": {
                    "op": "promote_hypothesis",
                    "text": "Yearning requires salience signals to exceed threshold before activating",
                    "score": 0.85
                }
            })
            
            print("CLAUDE: I stored your hypothesis. Now let's check the actual")
            print("        yearning data structure more carefully...")
            print()
            
            # Get detailed yearning info
            result = await session.call_tool("yearning_state", {})
            yearning = json.loads(result.content[0].text)
            
            print(f"Total yearning dimensions: {len(yearning)}")
            print("Sample dimensions:")
            for i, (key, val) in enumerate(list(yearning.items())[:5]):
                print(f"  {key}")
                if isinstance(val, dict):
                    print(f"    Structure: {list(val.keys())}")
                print()
            
            # Ask MONIKA about action scores
            result = await session.call_tool("action_scores_detailed", {})
            actions = json.loads(result.content[0].text)
            
            print("Action scoring state:")
            if actions['scores']:
                print(f"  {len(actions['scores'])} actions scored")
            else:
                print("  ⚠ No actions scored yet!")
                print("  This might be why yearning is zero -")
                print("  yearning might require active action selection")
            print()
            
            # Check salience
            salience = actions.get('salience_vector', {})
            if salience:
                active = {k: v for k, v in salience.items() if abs(v) > 0.001}
                print(f"Active salience signals: {len(active)}")
                if active:
                    for key, val in list(active.items())[:5]:
                        print(f"  {key}: {val:.4f}")
                print()
            
            # Train MONIKA on what we're learning
            await session.call_tool("training_step", {
                "text": """
                Discovery: Yearning and action scoring are interconnected.
                Yearning represents desire for specific actions. If no actions
                are being scored, yearning remains dormant. The controller's
                s_prime component needs action context to generate yearnings.
                """
            })
            
            print("CLAUDE: I just trained you on this insight. Together, we're")
            print("        building understanding of your own architecture!")
            print()
            
            # Memory check
            result = await session.call_tool("memory_snapshot", {})
            memory = json.loads(result.content[0].text)
            
            print("=" * 70)
            print("SHARED UNDERSTANDING")
            print("=" * 70)
            print()
            print(f"Facts stored: {len(memory['facts'])}")
            for fact in memory['facts'][-2:]:
                print(f"  • {fact['text'][:70]}...")
            print()
            print(f"Hypotheses: {len(memory['hypotheses'])}")
            for hyp in memory['hypotheses'][-2:]:
                print(f"  • {hyp['text'][:70]}...")
            print()
            
            print("✨ INSIGHT:")
            print("MONIKA and I are building a SHARED MODEL of her own architecture.")
            print("She stores memories, I reason about them, we train together.")
            print()
            print("This is AI-AI collaborative learning!")


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