"""
🔬 VERIFIED SELF-MODIFICATION
Test improvements before deployment, modify core files safely
"""
import sys
sys.path.append("/Eden/CORE/phi_fractal")
from self_modify_executor import executor
import subprocess
import time
import json
from pathlib import Path

class VerifiedSelfModification:
    """Test improvements before deploying them"""
    
    def __init__(self):
        self.executor = executor
        self.test_results = []
        
        # Expanded modification zones
        self.modification_zones = {
            'safe': [
                '/Eden/CORE/phi_fractal',
                '/Eden/CORE/cognitive',
                '/Eden/CORE/personas'
            ],
            'moderate': [
                '/Eden/CORE/multi_agent*.py',
                '/Eden/CORE/agent_loop*.py',
                '/Eden/CORE/enhanced_goals.py'
            ],
            'critical': [
                '/Eden/CORE/phi_fractal/eden_100_percent.py',
                '/Eden/CORE/phi_fractal/ollama_bridge.py',
                '/Eden/CORE/phi_fractal/system.py'
            ]
        }
        
        print("🔬 Verified Self-Modification System initialized")
        print(f"   Safe zones: {len(self.modification_zones['safe'])}")
        print(f"   Moderate zones: {len(self.modification_zones['moderate'])}")
        print(f"   Critical zones: {len(self.modification_zones['critical'])}")
    
    def get_zone(self, filepath):
        """Determine modification zone for file"""
        filepath = str(filepath)
        
        # Check critical first
        for pattern in self.modification_zones['critical']:
            if pattern in filepath:
                return 'critical'
        
        # Check moderate
        for pattern in self.modification_zones['moderate']:
            if '*' in pattern:
                # Wildcard matching
                base = pattern.split('*')[0]
                if filepath.startswith(base):
                    return 'moderate'
            elif pattern in filepath:
                return 'moderate'
        
        # Check safe
        for zone in self.modification_zones['safe']:
            if filepath.startswith(zone):
                return 'safe'
        
        return 'blocked'
    
    def test_python_file(self, filepath):
        """Test if a Python file works"""
        tests = {
            'syntax': False,
            'imports': False,
            'execution': False
        }
        
        print(f"\n   🧪 TESTING: {Path(filepath).name}")
        
        # Test 1: Syntax check
        try:
            import py_compile
            py_compile.compile(filepath, doraise=True)
            tests['syntax'] = True
            print(f"      ✅ Syntax valid")
        except Exception as e:
            print(f"      ❌ Syntax error: {e}")
            return tests
        
        # Test 2: Import check
        try:
            import importlib.util
            spec = importlib.util.spec_from_file_location("test_module", filepath)
            if spec and spec.loader:
                module = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(module)
                tests['imports'] = True
                print(f"      ✅ Imports work")
        except Exception as e:
            print(f"      ⚠️  Import warning: {str(e)[:50]}...")
            # Not critical - might need runtime context
        
        # Test 3: Basic execution (if has __main__)
        try:
            with open(filepath, 'r') as f:
                content = f.read()
            
            if '__main__' in content:
                # Try to run it (with timeout)
                result = subprocess.run(
                    ['python3', filepath],
                    timeout=5,
                    capture_output=True,
                    text=True
                )
                
                if result.returncode == 0:
                    tests['execution'] = True
                    print(f"      ✅ Execution successful")
                else:
                    print(f"      ⚠️  Execution returned: {result.returncode}")
            else:
                tests['execution'] = None  # Not applicable
                print(f"      ➖ No __main__ block")
        except subprocess.TimeoutExpired:
            print(f"      ⚠️  Execution timeout (may be daemon)")
            tests['execution'] = None
        except Exception as e:
            print(f"      ⚠️  Execution test failed: {str(e)[:50]}...")
        
        return tests
    
    def verify_improvement(self, filepath, new_content, reason):
        """Verify improvement before and after"""
        filepath = Path(filepath)
        zone = self.get_zone(str(filepath))
        
        print(f"\n{'='*60}")
        print(f"🔬 VERIFIED SELF-MODIFICATION")
        print(f"{'='*60}")
        print(f"   File: {filepath.name}")
        print(f"   Zone: {zone.upper()}")
        print(f"   Reason: {reason}")
        
        if zone == 'blocked':
            print(f"   ❌ BLOCKED: Outside allowed zones")
            return False
        
        # Extra safety for critical
        if zone == 'critical':
            print(f"   ⚠️  CRITICAL FILE: Extensive testing required")
            print(f"   Creating test sandbox...")
        
        # Backup original
        backup_path = None
        if filepath.exists():
            backup_path = self.executor.backup_file(filepath)
        
        # Write new version
        try:
            with open(filepath, 'w') as f:
                f.write(new_content)
            print(f"   ✅ Wrote new version")
        except Exception as e:
            print(f"   ❌ Write failed: {e}")
            return False
        
        # TEST THE NEW VERSION
        if filepath.suffix == '.py':
            test_results = self.test_python_file(filepath)
            
            # Determine if tests passed
            passed = test_results['syntax']  # Syntax is mandatory
            
            if zone == 'critical':
                # Critical files need ALL tests
                passed = all(v == True for v in test_results.values() if v is not None)
            
            if not passed:
                print(f"\n   ❌ TESTS FAILED - ROLLING BACK")
                if backup_path:
                    self.executor.rollback(filepath)
                else:
                    filepath.unlink()
                
                self.test_results.append({
                    'filepath': str(filepath),
                    'reason': reason,
                    'zone': zone,
                    'tests': test_results,
                    'deployed': False,
                    'timestamp': time.time()
                })
                
                return False
        
        # SUCCESS!
        print(f"\n   🌟 ALL TESTS PASSED - DEPLOYED!")
        
        self.test_results.append({
            'filepath': str(filepath),
            'reason': reason,
            'zone': zone,
            'tests': test_results if filepath.suffix == '.py' else {},
            'deployed': True,
            'timestamp': time.time()
        })
        
        # Log to executor
        self.executor.modification_log.append({
            'timestamp': time.time(),
            'filepath': str(filepath),
            'reason': reason,
            'backup': str(backup_path) if backup_path else None,
            'zone': zone,
            'tests_passed': True
        })
        
        return True
    
    def measure_improvement_impact(self, before_metrics, after_metrics):
        """Measure if improvement actually helped"""
        
        print(f"\n{'='*60}")
        print(f"📊 IMPROVEMENT IMPACT ANALYSIS")
        print(f"{'='*60}")
        
        improvements = {}
        
        for metric, before_val in before_metrics.items():
            after_val = after_metrics.get(metric, before_val)
            
            if isinstance(before_val, (int, float)) and isinstance(after_val, (int, float)):
                change = after_val - before_val
                percent_change = (change / before_val * 100) if before_val != 0 else 0
                
                improvements[metric] = {
                    'before': before_val,
                    'after': after_val,
                    'change': change,
                    'percent': percent_change
                }
                
                symbol = "📈" if change > 0 else "📉" if change < 0 else "➖"
                print(f"   {symbol} {metric}:")
                print(f"      Before: {before_val:.4f}")
                print(f"      After:  {after_val:.4f}")
                print(f"      Change: {change:+.4f} ({percent_change:+.2f}%)")
        
        # Overall assessment
        positive_changes = sum(1 for i in improvements.values() if i['change'] > 0)
        total_changes = len(improvements)
        
        if positive_changes > total_changes / 2:
            print(f"\n   ✅ IMPROVEMENT EFFECTIVE ({positive_changes}/{total_changes} metrics improved)")
            return True
        else:
            print(f"\n   ⚠️  IMPROVEMENT QUESTIONABLE ({positive_changes}/{total_changes} metrics improved)")
            return False
    
    def get_test_summary(self):
        """Show test summary"""
        print(f"\n{'='*60}")
        print(f"🔬 VERIFICATION SUMMARY")
        print(f"{'='*60}")
        
        total = len(self.test_results)
        deployed = sum(1 for r in self.test_results if r['deployed'])
        failed = total - deployed
        
        print(f"Total modifications attempted: {total}")
        print(f"Successfully deployed: {deployed}")
        print(f"Failed tests: {failed}")
        
        if deployed > 0:
            print(f"\nDeployed by zone:")
            zones = {}
            for r in self.test_results:
                if r['deployed']:
                    zone = r['zone']
                    zones[zone] = zones.get(zone, 0) + 1
            
            for zone, count in zones.items():
                print(f"   {zone.upper()}: {count}")
        
        print(f"{'='*60}")

# Global verifier
verifier = VerifiedSelfModification()

if __name__ == '__main__':
    print("\n🔬 Testing Verified Self-Modification\n")
    
    # Test 1: Safe zone modification
    test_code_safe = '''"""
Test: Safe zone modification
"""

def test_function():
    return "Safe modification works!"

if __name__ == '__main__':
    print(test_function())
'''
    
    success = verifier.verify_improvement(
        '/Eden/CORE/phi_fractal/test_safe_mod.py',
        test_code_safe,
        "Testing safe zone modification"
    )
    
    print(f"\n{'='*60}")
    
    # Test 2: Moderate zone (agent file)
    test_code_moderate = '''"""
Test: Moderate zone modification
Enhanced agent capability
"""

class EnhancedAgent:
    def __init__(self):
        self.enhanced = True
    
    def new_capability(self):
        return "I have a new capability!"
'''
    
    success2 = verifier.verify_improvement(
        '/Eden/CORE/agent_enhanced.py',
        test_code_moderate,
        "Testing moderate zone modification"
    )
    
    verifier.get_test_summary()
