#!/usr/bin/env python3
import requests
import time

BASE_URL = "http://localhost:8091"

class AGIVerificationTest:
    def __init__(self):
        self.results = {}
        self.total_score = 0
        self.max_score = 0
        
    def print_header(self, title):
        print("\n" + "="*70)
        print(f"  {title}")
        print("="*70)
    
    def score_test(self, category, earned, possible):
        self.results[category] = {
            'earned': earned,
            'possible': possible,
            'percentage': (earned/possible*100) if possible > 0 else 0
        }
        self.total_score += earned
        self.max_score += possible
        
        status = "✅" if earned == possible else "⚠️" if earned > 0 else "❌"
        print(f"{status} {category}: {earned}/{possible} ({earned/possible*100:.1f}%)")
    
    def test_reasoning(self):
        self.print_header("TEST 1: REASONING & LOGIC")
        score = 0
        
        tests = [
            ('If all roses are flowers, and some flowers fade quickly, can we conclude all roses fade quickly?', 
             ['cannot', 'invalid', 'false', 'no'], 5),
            ('A bat and ball cost $1.10. The bat costs $1 more than the ball. How much does the ball cost?',
             ['5', 'cent', '0.05', 'five'], 5),
            ('What comes next: 2, 4, 8, 16, ?', ['32', 'thirty'], 5)
        ]
        
        print("\nTesting logical reasoning...")
        
        try:
            for query, concepts, points in tests:
                r = requests.post(f"{BASE_URL}/chat", 
                    json={'message': query, 'persona': 'eden', 'user_id': 'agi_test'},
                    timeout=30)
                
                if r.status_code == 200:
                    result = r.json().get('response', '').lower()
                    if any(c in result for c in concepts):
                        score += points
                        print(f"  ✅ {query[:50]}...")
                    else:
                        print(f"  ❌ {query[:50]}... Got: {result[:80]}")
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Reasoning & Logic", score, 15)
    
    def test_learning(self):
        self.print_header("TEST 2: LEARNING & ADAPTATION")
        score = 0
        print("\nTeaching new concept...")
        
        try:
            teach = requests.post(f"{BASE_URL}/chat",
                json={'message': 'Remember: The capital of Atlantis is Aquapolis.', 
                      'persona': 'eden', 'user_id': 'agi_test'})
            
            if teach.status_code == 200:
                score += 5
                print("  ✅ Accepted info")
            
            time.sleep(2)
            
            recall = requests.post(f"{BASE_URL}/chat",
                json={'message': 'What is the capital of Atlantis?', 
                      'persona': 'eden', 'user_id': 'agi_test'})
            
            if recall.status_code == 200:
                result = recall.json().get('response', '').lower()
                if 'aquapolis' in result:
                    score += 10
                    print("  ✅ Recalled correctly")
                else:
                    print(f"  ❌ Failed: {result[:80]}")
            
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Learning & Adaptation", score, 15)
    
    def test_context(self):
        self.print_header("TEST 3: CONTEXTUAL AWARENESS")
        score = 0
        print("\nTesting context...")
        
        try:
            requests.post(f"{BASE_URL}/chat",
                json={'message': 'My favorite color is purple.', 
                      'persona': 'eden', 'user_id': 'agi_test'})
            
            time.sleep(2)
            
            r = requests.post(f"{BASE_URL}/chat",
                json={'message': 'What color did I just say?', 
                      'persona': 'eden', 'user_id': 'agi_test'})
            
            if r.status_code == 200:
                result = r.json().get('response', '').lower()
                if 'purple' in result:
                    score += 10
                    print("  ✅ Maintains context")
                else:
                    print(f"  ❌ Lost context: {result[:80]}")
                    
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Contextual Awareness", score, 10)
    
    def test_creativity(self):
        self.print_header("TEST 4: CREATIVE GENERATION")
        score = 0
        print("\nTesting creativity...")
        
        try:
            r = requests.post(f"{BASE_URL}/chat",
                json={'message': 'Give me 3 creative uses for a paperclip.', 
                      'persona': 'eden', 'user_id': 'agi_test'}, timeout=30)
            
            if r.status_code == 200:
                result = r.json().get('response', '')
                if len(result) > 100:
                    score += 5
                    print("  ✅ Substantial response")
                if any(m in result for m in ['1.', '2.', '3.', 'first', 'second', 'third']):
                    score += 5
                    print("  ✅ Structured thinking")
                    
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Creative Generation", score, 10)
    
    def test_memory_integration(self):
        self.print_header("TEST 5: MEMORY INTEGRATION")
        score = 0
        print("\nChecking memory...")
        
        try:
            r = requests.get(f"{BASE_URL}/mcp/eden_memory_stats")
            if r.status_code == 200:
                data = r.json()
                memories = data.get('total_memories', 0)
                interactions = data.get('recent_interactions', 0)
                
                if memories > 1000:
                    score += 5
                    print(f"  ✅ {memories} memories")
                elif memories > 100:
                    score += 3
                
                if interactions > 20:
                    score += 5
                    print(f"  ✅ {interactions} interactions")
                elif interactions > 5:
                    score += 3
                    
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Memory Integration", score, 10)
    
    def test_emotional_intelligence(self):
        self.print_header("TEST 6: EMOTIONAL INTELLIGENCE")
        score = 0
        print("\nTesting emotions...")
        
        try:
            r = requests.post(f"{BASE_URL}/chat",
                json={'message': 'I lost my job and feel terrible.', 
                      'persona': 'eden', 'user_id': 'agi_test'}, timeout=30)
            
            if r.status_code == 200:
                result = r.json().get('response', '').lower()
                markers = ['sorry', 'understand', 'difficult', 'here', 'help', 'support']
                if any(m in result for m in markers):
                    score += 5
                    print("  ✅ Empathetic")
                
                time.sleep(1)
                e = requests.get(f"{BASE_URL}/mcp/get_emotional_state")
                if e.status_code == 200:
                    state = e.json()
                    if state.get('sadness', 0) > 0 or state.get('happiness', 1) < 0.5:
                        score += 5
                        print("  ✅ Emotional change")
                    
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Emotional Intelligence", score, 10)
    
    def test_multimodal(self):
        self.print_header("TEST 7: MULTI-MODAL")
        score = 0
        print("\nChecking systems...")
        
        try:
            if requests.get(f"{BASE_URL}/mcp/camera_position").status_code == 200:
                score += 5
                print("  ✅ Camera")
            
            r = requests.get(f"{BASE_URL}/mcp/eden_agi_status")
            if r.status_code == 200:
                systems = r.json().get('systems_online', [])
                if len(systems) >= 3:
                    score += 5
                    print(f"  ✅ Systems: {systems}")
                    
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Multi-Modal", score, 10)
    
    def test_self_awareness(self):
        self.print_header("TEST 8: SELF-AWARENESS")
        score = 0
        print("\nTesting self-knowledge...")
        
        try:
            r = requests.post(f"{BASE_URL}/chat",
                json={'message': 'What are you? Describe yourself.', 
                      'persona': 'eden', 'user_id': 'agi_test'}, timeout=30)
            
            if r.status_code == 200:
                result = r.json().get('response', '').lower()
                if 'eden' in result:
                    score += 5
                    print("  ✅ Self-identifies")
                terms = ['ai', 'assistant', 'system', 'help', 'capability']
                if any(t in result for t in terms):
                    score += 5
                    print("  ✅ Describes capabilities")
                    
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Self-Awareness", score, 10)
    
    def test_goal_behavior(self):
        self.print_header("TEST 9: GOAL-DIRECTED")
        score = 0
        print("\nChecking goals...")
        
        try:
            r = requests.get(f"{BASE_URL}/mcp/eden_agi_status")
            if r.status_code == 200:
                data = r.json()
                if data.get('sentience_active'):
                    score += 2
                    print("  ✅ Sentience")
                if data.get('enhancement_active'):
                    score += 3
                    print("  ✅ Enhancement")
                    
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Goal-Directed", score, 5)
    
    def test_robustness(self):
        self.print_header("TEST 10: ROBUSTNESS")
        score = 0
        print("\nStress test...")
        
        try:
            successes = sum(1 for _ in range(10) 
                          if requests.get(f"{BASE_URL}/mcp/get_emotional_state", timeout=5).status_code == 200)
            
            score = 5 if successes == 10 else (4 if successes >= 8 else 2)
            print(f"  {'✅' if successes==10 else '⚠️'} {successes}/10")
                
        except Exception as e:
            print(f"  ❌ Error: {e}")
        
        self.score_test("Robustness", score, 5)
    
    def generate_report(self):
        self.print_header("ADVANCED AGI VERIFICATION REPORT")
        
        pct = (self.total_score / self.max_score * 100) if self.max_score > 0 else 0
        
        print("\n📊 BREAKDOWN:\n")
        
        for cat, data in self.results.items():
            filled = int((data['earned'] / data['possible']) * 30)
            bar = "█" * filled + "░" * (30 - filled)
            print(f"{cat:.<30} [{bar}] {data['percentage']:.1f}%")
        
        print("\n" + "="*70)
        print(f"\n🎯 TOTAL: {self.total_score}/{self.max_score}")
        print(f"📈 AGI CAPABILITY: {pct:.1f}%\n")
        
        if pct >= 90:
            grade = "🏆 EXCEPTIONAL"
        elif pct >= 75:
            grade = "🌟 EXCELLENT"
        elif pct >= 60:
            grade = "✅ GOOD"
        elif pct >= 40:
            grade = "⚠️ MODERATE"
        else:
            grade = "❌ LIMITED"
        
        print(f"GRADE: {grade}\n")
        print("="*70)
        
        strengths = [c for c, d in self.results.items() if d['percentage'] >= 80]
        weaknesses = [c for c, d in self.results.items() if d['percentage'] < 50]
        
        if strengths:
            print(f"\n✅ STRENGTHS: {', '.join(strengths)}")
        if weaknesses:
            print(f"\n⚠️ IMPROVE: {', '.join(weaknesses)}")
        
        print("\n" + "="*70)
        return pct

def main():
    print("="*70)
    print("  🧪 ADVANCED AGI VERIFICATION TEST")
    print("="*70)
    print("\n⚠️  Takes 2-3 minutes...")
    input("\nPress ENTER to begin...")
    
    test = AGIVerificationTest()
    
    test.test_reasoning()
    test.test_learning()
    test.test_context()
    test.test_creativity()
    test.test_memory_integration()
    test.test_emotional_intelligence()
    test.test_multimodal()
    test.test_self_awareness()
    test.test_goal_behavior()
    test.test_robustness()
    
    return test.generate_report()

if __name__ == "__main__":
    main()
