"""
Adaptive Strategies - Dynamic strategy adaptation and learning
"""

class AdaptiveStrategies:
    def __init__(self):
        self.strategy_performance = {}
        self.context_history = []
        
    def evaluate_context(self, task, constraints):
        """Evaluate task context to select strategy"""
        context = {
            "task": task,
            "complexity": self.estimate_complexity(task),
            "constraints": constraints,
            "resources": self.assess_resources(constraints)
        }
        
        self.context_history.append(context)
        return context
    
    def estimate_complexity(self, task):
        """Estimate task complexity"""
        task_lower = task.lower()
        
        complexity_indicators = {
            "simple": ["basic", "easy", "simple", "straightforward"],
            "moderate": ["moderate", "average", "standard"],
            "complex": ["complex", "difficult", "hard", "challenging"],
            "very_complex": ["very complex", "extremely", "highly complex"]
        }
        
        for level, indicators in complexity_indicators.items():
            if any(ind in task_lower for ind in indicators):
                return level
        
        # Default based on description length
        if len(task.split()) < 5:
            return "simple"
        elif len(task.split()) < 15:
            return "moderate"
        else:
            return "complex"
    
    def assess_resources(self, constraints):
        """Assess available resources"""
        resources = {
            "time": "unlimited",
            "memory": "unlimited",
            "compute": "available"
        }
        
        if constraints:
            if "time" in str(constraints).lower():
                resources["time"] = "limited"
            if "memory" in str(constraints).lower():
                resources["memory"] = "limited"
        
        return resources
    
    def select_adaptive_strategy(self, context):
        """Select best strategy for context"""
        complexity = context["complexity"]
        resources = context["resources"]
        
        # Strategy selection logic
        if complexity == "simple":
            if resources["time"] == "limited":
                strategy = "greedy_fast"
            else:
                strategy = "optimal_solution"
        
        elif complexity == "moderate":
            if resources["memory"] == "limited":
                strategy = "iterative_refinement"
            else:
                strategy = "divide_conquer"
        
        elif complexity in ["complex", "very_complex"]:
            if resources["time"] == "limited":
                strategy = "heuristic_approximation"
            else:
                strategy = "exhaustive_search"
        
        else:
            strategy = "adaptive_general"
        
        return {
            "strategy": strategy,
            "reasoning": f"Selected for {complexity} task with {resources['time']} time",
            "confidence": self.calculate_confidence(strategy, context)
        }
    
    def calculate_confidence(self, strategy, context):
        """Calculate confidence in strategy selection"""
        # Check past performance
        if strategy in self.strategy_performance:
            perf = self.strategy_performance[strategy]
            return perf["success_rate"]
        
        # Default confidence based on context match
        if context["complexity"] == "simple":
            return 0.9
        elif context["complexity"] == "moderate":
            return 0.75
        else:
            return 0.6
    
    def update_strategy_performance(self, strategy, success):
        """Learn from strategy outcomes"""
        if strategy not in self.strategy_performance:
            self.strategy_performance[strategy] = {
                "uses": 0,
                "successes": 0,
                "success_rate": 0.5
            }
        
        perf = self.strategy_performance[strategy]
        perf["uses"] += 1
        if success:
            perf["successes"] += 1
        
        perf["success_rate"] = perf["successes"] / perf["uses"]
        
        return perf
    
    def recommend_improvement(self, strategy, context):
        """Recommend strategy improvements"""
        improvements = []
        
        if strategy in self.strategy_performance:
            perf = self.strategy_performance[strategy]
            
            if perf["success_rate"] < 0.5:
                improvements.append("Consider alternative strategy")
            
            if perf["uses"] > 5 and perf["success_rate"] < 0.7:
                improvements.append("Strategy needs optimization")
        
        if context["complexity"] == "very_complex":
            improvements.append("Break into smaller sub-problems")
        
        return improvements if improvements else ["Strategy performing well"]

if __name__ == "__main__":
    print("ADAPTIVE STRATEGIES TEST")
    
    adaptive = AdaptiveStrategies()
    
    # Test 1: Simple task
    print("\n🎯 Task 1: Simple task with time constraint")
    context = adaptive.evaluate_context("Sort a small list", {"time": "limited"})
    result = adaptive.select_adaptive_strategy(context)
    print(f"   Complexity: {context['complexity']}")
    print(f"   Strategy: {result['strategy']}")
    print(f"   Confidence: {result['confidence']:.0%}")
    
    # Test 2: Complex task
    print("\n🎯 Task 2: Complex optimization")
    context = adaptive.evaluate_context("Optimize complex neural network architecture", {})
    result = adaptive.select_adaptive_strategy(context)
    print(f"   Complexity: {context['complexity']}")
    print(f"   Strategy: {result['strategy']}")
    
    # Test 3: Learning from outcomes
    print("\n📈 Learning from strategy outcomes:")
    adaptive.update_strategy_performance("greedy_fast", success=True)
    adaptive.update_strategy_performance("greedy_fast", success=True)
    adaptive.update_strategy_performance("greedy_fast", success=False)
    perf = adaptive.strategy_performance["greedy_fast"]
    print(f"   Strategy: greedy_fast")
    print(f"   Success rate: {perf['success_rate']:.0%} ({perf['successes']}/{perf['uses']})")
    
    print("\n🔄 Eden now has:")
    print("   - Context evaluation")
    print("   - Adaptive strategy selection")
    print("   - Performance tracking")
    print("   - Strategy improvement recommendations")
    
    print("\n✅ ADAPTIVE STRATEGIES OPERATIONAL")
