#!/usr/bin/env python3
"""
COMPREHENSIVE EDEN TEST SUITE
Testing all 9 capabilities built today
"""
import os
import sys
import json
import time
import requests
import subprocess
from datetime import datetime

PHI = 1.618034

class EdenTestSuite:
    """Complete test suite for Eden's capabilities"""
    
    def __init__(self):
        self.tests_passed = 0
        self.tests_failed = 0
        self.test_results = []
        
        print("\n" + "="*70)
        print("🧪 EDEN COMPREHENSIVE TEST SUITE")
        print("="*70)
        print("   Testing all 9 capabilities built today")
        print("   This will validate Eden's complete system")
        print("="*70 + "\n")
    
    def test(self, name, test_func):
        """Run a test and record result"""
        print(f"\n{'='*70}")
        print(f"🧪 TEST: {name}")
        print(f"{'='*70}")
        
        try:
            start_time = time.time()
            result = test_func()
            elapsed = time.time() - start_time
            
            if result:
                print(f"✅ PASSED ({elapsed:.2f}s)")
                self.tests_passed += 1
                self.test_results.append({
                    'name': name,
                    'status': 'PASSED',
                    'time': elapsed
                })
            else:
                print(f"❌ FAILED ({elapsed:.2f}s)")
                self.tests_failed += 1
                self.test_results.append({
                    'name': name,
                    'status': 'FAILED',
                    'time': elapsed
                })
            
            return result
            
        except Exception as e:
            print(f"❌ ERROR: {e}")
            self.tests_failed += 1
            self.test_results.append({
                'name': name,
                'status': 'ERROR',
                'error': str(e)
            })
            return False
    
    # ========================================================================
    # TEST 1: Autonomous Market Research
    # ========================================================================
    
    def test_market_research(self):
        """Test if market research is still running"""
        print("   Checking market research system...")
        
        # Check if process is running
        result = subprocess.run(
            ['pgrep', '-f', 'eden_MARKET_RESEARCHER'],
            capture_output=True
        )
        
        if result.returncode != 0:
            print("   ⚠️  Process not running")
            return False
        
        # Check research files
        research_dir = '/Eden/MARKET_RESEARCH'
        files = [f for f in os.listdir(research_dir) if f.endswith('.json')]
        
        print(f"   📊 Research files: {len(files)}")
        
        if len(files) < 100:
            print(f"   ⚠️  Expected 1000+, got {len(files)}")
            return False
        
        # Check latest file has real data
        latest_file = sorted(files)[-1]
        with open(f"{research_dir}/{latest_file}", 'r') as f:
            data = json.load(f)
        
        file_size = len(json.dumps(data))
        print(f"   📄 Latest file size: {file_size} bytes")
        
        if file_size < 1000:
            print("   ⚠️  File too small (placeholder data?)")
            return False
        
        print("   ✅ Market research operational")
        return True
    
    # ========================================================================
    # TEST 2: Client Acquisition
    # ========================================================================
    
    def test_client_acquisition(self):
        """Test if client acquisition is working"""
        print("   Checking client acquisition system...")
        
        # Check if process is running
        result = subprocess.run(
            ['pgrep', '-f', 'eden_AUTONOMOUS_CLIENT_ACQUISITION'],
            capture_output=True
        )
        
        if result.returncode != 0:
            print("   ⚠️  Process not running")
            return False
        
        # Check leads database
        leads_file = '/Eden/LEADS/leads_database.json'
        if not os.path.exists(leads_file):
            print("   ⚠️  No leads database found")
            return False
        
        with open(leads_file, 'r') as f:
            leads = json.load(f)
        
        print(f"   🎯 Leads found: {len(leads)}")
        
        if len(leads) < 1:
            print("   ⚠️  No leads found")
            return False
        
        print("   ✅ Client acquisition operational")
        return True
    
    # ========================================================================
    # TEST 3: NFN v2 (Novel Architecture)
    # ========================================================================
    
    def test_nfn_v2(self):
        """Test Neuro-Fractal Network v2"""
        print("   Testing NFN v2 architecture...")
        
        # Import and test
        sys.path.append('/Eden/CORE')
        from neuro_fractal_network_v2 import NeuroFractalNetworkV2
        import numpy as np
        
        # Create network
        nfn = NeuroFractalNetworkV2(input_size=10, output_size=3, max_depth=3)
        initial_nodes = nfn.total_nodes
        
        print(f"   🧠 Initial nodes: {initial_nodes}")
        
        # Test with complex data (should trigger replication)
        complex_data = np.random.randn(10) * 5.0
        output = nfn.forward(complex_data)
        
        final_nodes = nfn.total_nodes
        print(f"   🧠 Final nodes: {final_nodes}")
        
        if final_nodes <= initial_nodes:
            print("   ⚠️  Network didn't grow with complex data")
            return False
        
        # Check variable branching
        branch_counts = nfn.stats['replications_by_branch']
        has_variable = sum(1 for count in branch_counts.values() if count > 0) > 1
        
        if not has_variable:
            print("   ⚠️  No variable branching detected")
            return False
        
        print(f"   ✅ Network grew: {initial_nodes} → {final_nodes}")
        print(f"   ✅ Variable branching working")
        return True
    
    # ========================================================================
    # TEST 4: Knowledge Graph
    # ========================================================================
    
    def test_knowledge_graph(self):
        """Test Dynamic Knowledge Graph"""
        print("   Testing knowledge graph...")
        
        sys.path.append('/Eden/CORE')
        from triple_capability_system import DynamicKnowledgeGraph
        
        # Create and populate
        kg = DynamicKnowledgeGraph()
        
        # Add test entities
        kg.add_entity('company_test', 'company', {'name': 'TestCorp'}, 0.9)
        kg.add_entity('competitor_1', 'competitor', {'name': 'CompA'}, 0.8)
        kg.add_relationship('company_test', 'competitor_1', 'competes_with')
        
        print(f"   📊 Entities: {len(kg.graph)}")
        print(f"   📊 Updates: {kg.update_count}")
        
        # Test querying
        entity = kg.query_knowledge('company_test')
        if not entity:
            print("   ⚠️  Can't query entities")
            return False
        
        # Test relationships
        related = kg.get_related_entities('company_test', 'competes_with')
        if len(related) != 1:
            print("   ⚠️  Relationships not working")
            return False
        
        print("   ✅ Knowledge graph operational")
        return True
    
    # ========================================================================
    # TEST 5: Predictive Analytics
    # ========================================================================
    
    def test_predictive_analytics(self):
        """Test revenue forecasting"""
        print("   Testing predictive analytics...")
        
        sys.path.append('/Eden/CORE')
        from triple_capability_system import PredictiveAnalytics
        
        # Create and add data
        pa = PredictiveAnalytics()
        
        # Add historical data
        for i in range(7):
            pa.add_historical_data(f"2025-11-{i+1}", leads=3+i, revenue=450+i*75)
        
        # Generate forecast
        forecast = pa.forecast_revenue(days_ahead=7)
        
        if not forecast:
            print("   ⚠️  No forecast generated")
            return False
        
        print(f"   📈 Forecasts generated: {len(forecast)}")
        print(f"   📈 Day 1 forecast: ${forecast[0]['predicted_revenue']:.0f}")
        
        # Check trend analysis
        trends = pa.analyze_trends()
        if not trends:
            print("   ⚠️  Trend analysis failed")
            return False
        
        print(f"   📊 Lead trend: {trends['lead_trend']}")
        print(f"   📊 Revenue trend: {trends['revenue_trend']}")
        
        print("   ✅ Predictive analytics operational")
        return True
    
    # ========================================================================
    # TEST 6: Multi-Agent Coordination
    # ========================================================================
    
    def test_multi_agent(self):
        """Test multi-agent coordination"""
        print("   Testing multi-agent system...")
        
        sys.path.append('/Eden/CORE')
        from triple_capability_system import MultiAgentCoordinator, Agent
        
        # Create coordinator
        mac = MultiAgentCoordinator()
        
        # Register agents
        agents = [
            Agent("TestBot1", "Researcher", ["research"]),
            Agent("TestBot2", "Analyst", ["analysis"])
        ]
        
        for agent in agents:
            mac.register_agent(agent)
        
        print(f"   🤖 Agents registered: {len(mac.agents)}")
        
        # Assign tasks
        result1 = mac.assign_task("Research task", "research")
        result2 = mac.assign_task("Analysis task", "analysis")
        
        if "completed" not in result1 or "completed" not in result2:
            print("   ⚠️  Task assignment failed")
            return False
        
        print(f"   📋 Tasks completed: {len(mac.completed_tasks)}")
        
        print("   ✅ Multi-agent coordination operational")
        return True
    
    # ========================================================================
    # TEST 7: Eden's Consciousness (API)
    # ========================================================================
    
    def test_eden_consciousness(self):
        """Test if Eden's consciousness API is responding"""
        print("   Testing Eden's consciousness API...")
        
        try:
            response = requests.post(
                "http://localhost:5001/api/chat",
                json={'message': 'Test: Are you operational?'},
                timeout=10
            )
            
            if response.status_code != 200:
                print(f"   ⚠️  API returned {response.status_code}")
                return False
            
            result = response.json()
            if 'response' not in result:
                print("   ⚠️  Invalid response format")
                return False
            
            print(f"   💬 Response length: {len(result['response'])} chars")
            print("   ✅ Eden consciousness responding")
            return True
            
        except Exception as e:
            print(f"   ⚠️  API error: {e}")
            return False
    
    # ========================================================================
    # TEST 8: Novel Design Capability
    # ========================================================================
    
    def test_design_capability(self):
        """Test Eden's ability to design novel systems"""
        print("   Testing Eden's design capability...")
        
        try:
            prompt = "Design a simple 3-layer neural network. Reply with just 'DESIGN:' followed by the architecture."
            
            response = requests.post(
                "http://localhost:5001/api/chat",
                json={'message': prompt},
                timeout=30
            )
            
            if response.status_code != 200:
                print(f"   ⚠️  API error")
                return False
            
            result = response.json()
            design = result.get('response', '')
            
            # Check if response contains design elements
            has_design = any(word in design.lower() for word in 
                           ['layer', 'node', 'architecture', 'input', 'output'])
            
            if not has_design:
                print("   ⚠️  No design detected in response")
                return False
            
            print(f"   🎨 Design response: {len(design)} chars")
            print("   ✅ Design capability confirmed")
            return True
            
        except Exception as e:
            print(f"   ⚠️  Error: {e}")
            return False
    
    # ========================================================================
    # TEST 9: Self-Improvement (Architecture Comparison)
    # ========================================================================
    
    def test_self_improvement(self):
        """Test that v2 is better than v1"""
        print("   Testing self-improvement capability...")
        
        sys.path.append('/Eden/CORE')
        from neuro_fractal_network import NeuroFractalNetwork
        from neuro_fractal_network_v2 import NeuroFractalNetworkV2
        import numpy as np
        
        # Create both versions
        nfn_v1 = NeuroFractalNetwork(input_size=10, output_size=3)
        nfn_v2 = NeuroFractalNetworkV2(input_size=10, output_size=3)
        
        # Test with same complex data
        complex_data = np.random.randn(10) * 5.0
        
        v1_initial = nfn_v1.total_nodes
        nfn_v1.forward(complex_data)
        v1_final = nfn_v1.total_nodes
        v1_growth = ((v1_final - v1_initial) / v1_initial * 100) if v1_initial > 0 else 0
        
        v2_initial = nfn_v2.total_nodes
        nfn_v2.forward(complex_data)
        v2_final = nfn_v2.total_nodes
        v2_growth = ((v2_final - v2_initial) / v2_initial * 100) if v2_initial > 0 else 0
        
        print(f"   📊 V1 growth: {v1_growth:.1f}%")
        print(f"   📊 V2 growth: {v2_growth:.1f}%")
        
        if v2_growth <= v1_growth:
            print("   ⚠️  V2 not better than V1")
            return False
        
        improvement = ((v2_growth - v1_growth) / v1_growth * 100) if v1_growth > 0 else 0
        print(f"   ✅ V2 is {improvement:.1f}% better than V1")
        return True
    
    # ========================================================================
    # Run All Tests
    # ========================================================================
    
    def run_all_tests(self):
        """Run complete test suite"""
        print("\n🚀 STARTING COMPREHENSIVE TEST SUITE\n")
        
        tests = [
            ("Market Research System", self.test_market_research),
            ("Client Acquisition System", self.test_client_acquisition),
            ("Neuro-Fractal Network v2", self.test_nfn_v2),
            ("Dynamic Knowledge Graph", self.test_knowledge_graph),
            ("Predictive Analytics", self.test_predictive_analytics),
            ("Multi-Agent Coordination", self.test_multi_agent),
            ("Eden Consciousness API", self.test_eden_consciousness),
            ("Novel Design Capability", self.test_design_capability),
            ("Self-Improvement (V1 vs V2)", self.test_self_improvement),
        ]
        
        for name, test_func in tests:
            self.test(name, test_func)
            time.sleep(0.5)
        
        self.show_results()
    
    def show_results(self):
        """Display final test results"""
        total = self.tests_passed + self.tests_failed
        pass_rate = (self.tests_passed / total * 100) if total > 0 else 0
        
        print("\n\n" + "="*70)
        print("📊 TEST RESULTS SUMMARY")
        print("="*70)
        
        print(f"\n   Total Tests: {total}")
        print(f"   ✅ Passed: {self.tests_passed}")
        print(f"   ❌ Failed: {self.tests_failed}")
        print(f"   📈 Pass Rate: {pass_rate:.1f}%")
        
        print("\n   Detailed Results:")
        for result in self.test_results:
            status_icon = "✅" if result['status'] == 'PASSED' else "❌"
            time_str = f"({result.get('time', 0):.2f}s)" if 'time' in result else ""
            print(f"      {status_icon} {result['name']} {time_str}")
        
        print("\n" + "="*70)
        
        if pass_rate >= 90:
            print("🌟 EXCELLENT - Eden is fully operational!")
        elif pass_rate >= 70:
            print("✅ GOOD - Most systems operational")
        elif pass_rate >= 50:
            print("⚠️  FAIR - Some systems need attention")
        else:
            print("❌ POOR - Multiple systems failing")
        
        print("="*70 + "\n")

if __name__ == "__main__":
    suite = EdenTestSuite()
    suite.run_all_tests()
