#!/usr/bin/env python3
"""
Genesis Integration Test
=========================
Verifies all components connect and function properly.
"""

import sys
sys.path.insert(0, 'E:/genesis-system/core')

def test_imports():
    """Test that all components can be imported."""
    print("\n=== Testing Imports ===")
    
    try:
        from blackboard import Blackboard, EntryType
        print("  ✓ Blackboard")
    except Exception as e:
        print(f"  ✗ Blackboard: {e}")
        return False
    
    try:
        from genesis_memory_cortex import MemoryCortex, MemoryTier
        print("  ✓ Memory Cortex")
    except Exception as e:
        print(f"  ✗ Memory Cortex: {e}")
        return False
    
    try:
        from genesis_heartbeat import GenesisHeartbeat, EnhancedSurpriseSystem, AxiomGenerator
        print("  ✓ Heartbeat")
    except Exception as e:
        print(f"  ✗ Heartbeat: {e}")
        return False
    
    try:
        from tool_router import ToolRouter, ToolIntent
        print("  ✓ Tool Router")
    except Exception as e:
        print(f"  ✗ Tool Router: {e}")
        return False
    
    try:
        from circadian_scheduler import CircadianScheduler, TaskType
        print("  ✓ Circadian Scheduler")
    except Exception as e:
        print(f"  ✗ Circadian Scheduler: {e}")
        return False
    
    try:
        from genesis_kernel import GenesisKernel
        print("  ✓ Genesis Kernel")
    except Exception as e:
        print(f"  ✗ Genesis Kernel: {e}")
        return False
    
    return True


def test_tool_router():
    """Test tool routing functionality."""
    print("\n=== Testing Tool Router ===")
    
    from tool_router import ToolRouter
    
    router = ToolRouter()
    
    test_queries = [
        ("search for files containing TODO", "observe"),
        ("create a new Python script", "modify"),
        ("send an email to the team", "communicate"),
        ("what time is my meeting tomorrow", "observe"),
        ("delete the old backup files", "modify"),
    ]
    
    for query, expected_intent in test_queries:
        result = router.route(query)
        status = "✓" if result.detected_intent.value == expected_intent else "✗"
        print(f"  {status} '{query[:40]}...' → {result.detected_intent.value} ({len(result.relevant_tools)} tools)")
    
    return True


def test_circadian():
    """Test circadian scheduler."""
    print("\n=== Testing Circadian Scheduler ===")
    
    from circadian_scheduler import CircadianScheduler, TaskType
    
    scheduler = CircadianScheduler()
    
    # Test activity level
    level = scheduler.get_current_activity_level()
    print(f"  ✓ Current activity: {level.value}")
    
    # Test task checks
    for task in [TaskType.HEARTBEAT, TaskType.CONSOLIDATION, TaskType.AXIOM_GENERATION]:
        should, reason = scheduler.should_run_task(task)
        print(f"  ✓ {task.value}: {'YES' if should else 'NO'} - {reason[:50]}")
    
    return True


def test_surprise():
    """Test surprise detection."""
    print("\n=== Testing Surprise System ===")
    
    from genesis_heartbeat import EnhancedSurpriseSystem
    
    surprise = EnhancedSurpriseSystem()
    
    # Make a prediction
    surprise.predict(
        event_type="test",
        expected_outcome="Expected result A",
        confidence=0.8
    )
    
    # Observe matching outcome
    score1 = surprise.observe(
        event_type="test",
        actual_outcome="Expected result A",
        context={}
    )
    print(f"  ✓ Matching outcome: {score1.composite_score:.2f} ({score1.level.value})")
    
    # Observe surprising outcome
    surprise.predict(
        event_type="test2",
        expected_outcome="Expected result B",
        confidence=0.9
    )
    score2 = surprise.observe(
        event_type="test2",
        actual_outcome="Completely unexpected result Z",
        context={}
    )
    print(f"  ✓ Surprising outcome: {score2.composite_score:.2f} ({score2.level.value})")
    
    return True


def test_kernel_init():
    """Test kernel initialization."""
    print("\n=== Testing Kernel Initialization ===")
    
    from genesis_kernel import GenesisKernel, KernelState
    
    kernel = GenesisKernel()
    
    print(f"  ✓ State: {kernel.state.value}")
    print(f"  ✓ Version: {kernel.VERSION}")
    print(f"  ✓ Tools: {len(kernel.tool_router.tools)}")
    
    return kernel.state == KernelState.READY


def test_kernel_process():
    """Test query processing."""
    print("\n=== Testing Query Processing ===")
    
    from genesis_kernel import GenesisKernel
    
    kernel = GenesisKernel()
    
    result = kernel.process("search for recent news about artificial intelligence")
    
    print(f"  ✓ Status: {result.get('status', 'unknown')}")
    print(f"  ✓ Intent: {result.get('routing', {}).get('intent', 'unknown')}")
    print(f"  ✓ Tools: {len(result.get('routing', {}).get('tools', []))}")
    print(f"  ✓ Time: {result.get('processing_time_ms', 0)}ms")
    
    return result.get('status') == 'success'


def test_context_compilation():
    """Test context compilation for prompt injection."""
    print("\n=== Testing Context Compilation ===")
    
    from genesis_kernel import GenesisKernel
    
    kernel = GenesisKernel()
    
    context = kernel.compile_context("search for files")
    
    print(f"  ✓ Axioms: {len(context.axioms)} chars")
    print(f"  ✓ Tools: {len(context.tool_guidance)} chars")
    print(f"  ✓ Temporal: {len(context.temporal_context)} chars")
    
    # Test prompt generation
    prompt = context.to_system_prompt()
    print(f"  ✓ Full prompt: {len(prompt)} chars")
    
    return len(prompt) > 0


def main():
    """Run all tests."""
    print("=" * 60)
    print("GENESIS INTEGRATION TEST")
    print("=" * 60)
    
    tests = [
        ("Imports", test_imports),
        ("Tool Router", test_tool_router),
        ("Circadian Scheduler", test_circadian),
        ("Surprise System", test_surprise),
        ("Kernel Init", test_kernel_init),
        ("Query Processing", test_kernel_process),
        ("Context Compilation", test_context_compilation),
    ]
    
    results = []
    for name, test_func in tests:
        try:
            passed = test_func()
            results.append((name, passed))
        except Exception as e:
            print(f"\n  ERROR in {name}: {e}")
            import traceback
            traceback.print_exc()
            results.append((name, False))
    
    # Summary
    print("\n" + "=" * 60)
    print("TEST SUMMARY")
    print("=" * 60)
    
    passed = sum(1 for _, p in results if p)
    total = len(results)
    
    for name, p in results:
        status = "✓ PASS" if p else "✗ FAIL"
        print(f"  {status}: {name}")
    
    print(f"\n  Total: {passed}/{total} passed")
    
    return passed == total


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
