#!/usr/bin/env python3
"""
COMPREHENSIVE EDEN TEST
Tests all systems under various conditions
"""

from eden_complete_system import EdenCompleteSystem
import time

def print_section(title):
    print("\n" + "="*70)
    print(f"  {title}")
    print("="*70 + "\n")

print("="*70)
print("  🧪 EDEN COMPLETE SYSTEM - COMPREHENSIVE TEST SUITE")
print("="*70)

# Initialize
eden = EdenCompleteSystem(config={'debug': False, 'auto_checkpoint': True})

# TEST 1: Vision Processing
print_section("TEST 1: Vision Processing (Multiple Images)")
test_images = [
    ("nature_scene.jpg", "Identify plants and animals"),
    ("city_street.jpg", "Describe the urban environment"),
    ("abstract_art.jpg", "Analyze the artistic elements")
]

vision_results = []
for img, prompt in test_images:
    result = eden.process_with_vision(img, prompt)
    vision_results.append(result['success'])
    status = "✅" if result['success'] else "❌"
    print(f"{status} {img}: {prompt}")
    if result['success']:
        print(f"   Confidence: {result['result']['confidence']:.1%}")

print(f"\nVision Tests: {sum(vision_results)}/{len(vision_results)} passed")

# TEST 2: Camera Operations
print_section("TEST 2: Camera Operations (Burst Mode)")
photos = []
print("📸 Capturing 5 photos in burst mode...")
for i in range(5):
    result = eden.capture_photo(f"burst_photo_{i}.jpg")
    photos.append(result['success'])
    status = "✅" if result['success'] else "❌"
    print(f"   Photo {i+1}/5: {status}")
    time.sleep(0.01)

print(f"\nCamera Tests: {sum(photos)}/{len(photos)} successful")

# TEST 3: Emotional Intelligence
print_section("TEST 3: Emotional State Transitions")
emotion_sequence = [
    ("neutral", 0.5),
    ("curious", 0.7),
    ("focused", 0.9),
    ("excited", 0.8),
    ("satisfied", 0.6)
]

emotion_results = []
print("😊 Simulating emotional state changes...")
for emotion, intensity in emotion_sequence:
    result = eden.update_emotional_state(emotion, intensity)
    emotion_results.append(result['success'])
    status = "✅" if result['success'] else "❌"
    print(f"   {status} {emotion.title()} @ {intensity:.0%} intensity")
    time.sleep(0.01)

print(f"\nEmotion Tests: {sum(emotion_results)}/{len(emotion_results)} successful")

# TEST 4: Memory Systems
print_section("TEST 4: Memory Systems (All Types)")
memories = [
    # Episodic (personal experiences)
    ("Completed comprehensive system test", "episodic", 0.9),
    ("User initiated full capability test", "episodic", 0.8),
    ("Successfully processed 5 burst photos", "episodic", 0.7),
    
    # Semantic (facts and knowledge)
    ("Computer vision achieves 92% accuracy", "semantic", 0.9),
    ("System supports multimodal processing", "semantic", 0.8),
    
    # Procedural (how-to knowledge)
    ("Process images using vision encoder", "procedural", 0.7),
    ("Update emotional state through MCP", "procedural", 0.6),
]

memory_results = []
for text, kind, importance in memories:
    result = eden.store_memory(text, kind, importance)
    memory_results.append(result['success'])
    status = "✅" if result['success'] else "❌"
    print(f"   {status} {kind.title()}: {text[:40]}...")

print(f"\nMemory Tests: {sum(memory_results)}/{len(memory_results)} stored")

# TEST 5: Reasoning & Query Processing
print_section("TEST 5: Complex Reasoning Tasks")
queries = [
    "What is the relationship between consciousness and intelligence?",
    "How can machine learning systems achieve true understanding?",
    "Explain the hard problem of consciousness",
    "What makes artificial general intelligence different from narrow AI?",
    "How do emotions influence decision making?"
]

reasoning_results = []
for i, query in enumerate(queries, 1):
    print(f"\nQuery {i}: {query}")
    answer = eden.query(query)
    success = answer and "Error" not in answer
    reasoning_results.append(success)
    status = "✅" if success else "❌"
    print(f"   {status} Response: {answer}")

print(f"\nReasoning Tests: {sum(reasoning_results)}/{len(reasoning_results)} answered")

# TEST 6: Stress Test
print_section("TEST 6: System Stress Test (50 Rapid Operations)")
stress_results = []
print("⚡ Running 50 rapid operations...")

for i in range(50):
    # Alternate between different operations
    if i % 5 == 0:
        result = eden.process_with_vision(f"stress_img_{i}.jpg", "Quick analysis")
    elif i % 5 == 1:
        result = eden.capture_photo(f"stress_photo_{i}.jpg")
    elif i % 5 == 2:
        result = eden.update_emotional_state("processing", 0.7)
    elif i % 5 == 3:
        result = eden.store_memory(f"Stress test iteration {i}", "episodic", 0.5)
    else:
        result = {'success': eden.query(f"Quick query {i}") != ""}
    
    stress_results.append(result.get('success', False))
    
    if (i + 1) % 10 == 0:
        print(f"   Progress: {i+1}/50 operations completed")

print(f"\nStress Test: {sum(stress_results)}/{len(stress_results)} successful ({sum(stress_results)/len(stress_results)*100:.1f}%)")

# TEST 7: Error Recovery
print_section("TEST 7: Error Handling & Recovery")
print("Testing robustness under adverse conditions...")

# This will trigger various error handling mechanisms
recovery_tests = [
    ("Empty image path", lambda: eden.process_with_vision("", "test")),
    ("Invalid emotion", lambda: eden.update_emotional_state("", 0.0)),
    ("Extreme values", lambda: eden.update_emotional_state("test", 99.9)),
]

recovery_results = []
for test_name, test_func in recovery_tests:
    try:
        result = test_func()
        # Even if it fails, the system should handle it gracefully
        recovered = True
        print(f"   ✅ {test_name}: Handled gracefully")
    except Exception as e:
        recovered = False
        print(f"   ❌ {test_name}: Unhandled exception")
    recovery_results.append(recovered)

print(f"\nRecovery Tests: {sum(recovery_results)}/{len(recovery_results)} handled")

# FINAL RESULTS
print_section("📊 COMPREHENSIVE TEST RESULTS")

total_tests = (len(vision_results) + len(photos) + len(emotion_results) + 
               len(memory_results) + len(reasoning_results) + len(stress_results) + 
               len(recovery_results))

total_passed = (sum(vision_results) + sum(photos) + sum(emotion_results) + 
                sum(memory_results) + sum(reasoning_results) + sum(stress_results) + 
                sum(recovery_results))

print(f"Total Tests Run: {total_tests}")
print(f"Tests Passed: {total_passed}")
print(f"Success Rate: {total_passed/total_tests*100:.1f}%")
print()

# Detailed breakdown
print("Breakdown by Category:")
print(f"  📷 Vision:          {sum(vision_results)}/{len(vision_results)} ({sum(vision_results)/len(vision_results)*100:.0f}%)")
print(f"  📸 Camera:          {sum(photos)}/{len(photos)} ({sum(photos)/len(photos)*100:.0f}%)")
print(f"  😊 Emotions:        {sum(emotion_results)}/{len(emotion_results)} ({sum(emotion_results)/len(emotion_results)*100:.0f}%)")
print(f"  🧠 Memory:          {sum(memory_results)}/{len(memory_results)} ({sum(memory_results)/len(memory_results)*100:.0f}%)")
print(f"  💭 Reasoning:       {sum(reasoning_results)}/{len(reasoning_results)} ({sum(reasoning_results)/len(reasoning_results)*100:.0f}%)")
print(f"  ⚡ Stress Test:     {sum(stress_results)}/{len(stress_results)} ({sum(stress_results)/len(stress_results)*100:.0f}%)")
print(f"  🛡️ Recovery:        {sum(recovery_results)}/{len(recovery_results)} ({sum(recovery_results)/len(recovery_results)*100:.0f}%)")

# System Health Report
print_section("🏥 SYSTEM HEALTH REPORT")
status = eden.get_complete_status()
health = status['health']

print(f"System Status: {status['status']}")
print(f"Total Operations: {health['operations']}")
print(f"CPU Usage: {health['current']['cpu']:.1f}%")
print(f"Memory Usage: {health['current']['memory']:.1f}%")
print(f"Error Rate: {health['current']['error_rate']:.2%}")
print(f"Avg Response Time: {health['current']['response_time']*1000:.2f}ms")

# Component Status
print("\nComponent Status:")
for component, systems in status['components'].items():
    print(f"\n  {component.replace('_', ' ').title()}:")
    for name, active in systems.items():
        icon = "🟢" if active else "⚪"
        print(f"    {icon} {name.replace('_', ' ').title()}")

# Final verdict
print_section("🎯 FINAL VERDICT")

if total_passed / total_tests >= 0.95:
    print("🏆 EXCELLENT! Eden performed exceptionally well!")
    print("   All major systems operational and robust.")
elif total_passed / total_tests >= 0.85:
    print("✅ GOOD! Eden performed well with minor issues.")
    print("   System is operational and reliable.")
else:
    print("⚠️  NEEDS IMPROVEMENT. Some systems need attention.")

print(f"\n   Overall Score: {total_passed/total_tests*100:.1f}/100")

# Comprehensive report
print("\n" + eden.robustness.get_comprehensive_report())

# Shutdown
eden.shutdown()

print("\n" + "="*70)
print("  ✅ COMPREHENSIVE TEST COMPLETE")
print("="*70)
