"""
EDEN AGENT V5 - Enhanced Goal System
Multi-step action plans, better reasoning, goal tracking
"""
import sys
sys.path.append("/Eden/CORE")
from agent_loop_v4 import EdenAgentV4
from enhanced_goals import enhanced_goals
from datetime import datetime
import json

class EdenAgentV5(EdenAgentV4):
    """Agent with sophisticated goal pursuit"""
    
    def __init__(self):
        super().__init__()
        self.enhanced_goals = enhanced_goals
        self.active_plans = {}
        self.completed_steps = 0
        print("🎯 Enhanced goal system enabled (6 categories, multi-step plans)")
    
    def perceive(self):
        """Enhanced perception with plan tracking"""
        obs = super().perceive()
        obs['active_plans'] = len(self.active_plans)
        return obs
    
    def _plan_progress(self, plan):
        """Calculate progress percentage"""
        total = len(plan['steps'])
        completed = sum(1 for s in plan['steps'] if s['status'] == 'completed')
        return completed / total if total > 0 else 0
    
    def reason(self, obs):
        """Enhanced reasoning with plan execution"""
        decisions = super().reason(obs)
        
        goals = obs.get('goals_system', {})
        if goals.get('has_goals') and goals.get('focus'):
            focus = goals['focus']
            goal_id = focus['id']
            
            if goal_id not in self.active_plans:
                plan = self.enhanced_goals.create_action_plan(focus)
                self.active_plans[goal_id] = plan
                print(f"   📋 Created {plan['category']} plan for: {focus['topic']}")
                print(f"      Steps: {len(plan['steps'])}, Est. cycles: {plan['estimated_cycles']}")
        
        for goal_id, plan in list(self.active_plans.items()):
            next_step = self._get_next_step(plan)
            
            if next_step:
                decisions.insert(0, {
                    'action': 'execute_plan_step',
                    'priority': 0.85,
                    'reason': f"Continue {plan['category']} work on {plan['topic']}",
                    'risk': 'low',
                    'data': {'step': next_step, 'plan': plan, 'goal_id': goal_id}
                })
            else:
                progress = self._plan_progress(plan)
                if progress >= 1.0:
                    print(f"   ✅ Completed plan for: {plan['topic']}")
                    del self.active_plans[goal_id]
        
        return decisions
    
    def _get_next_step(self, plan):
        """Get next pending step in plan"""
        for step in plan['steps']:
            if step['status'] == 'pending':
                return step
        return None
    
    def _execute(self, decision):
        """Enhanced execution with plan steps"""
        action = decision['action']
        
        if action == 'execute_plan_step':
            data = decision['data']
            step = data['step']
            plan = data['plan']
            
            success = self.enhanced_goals.execute_step(step, {
                'goal_id': data['goal_id'],
                'category': plan['category']
            })
            
            if success:
                self.completed_steps += 1
                progress = self._plan_progress(plan)
                print(f"   ✓ {step['action']} ({plan['topic']})")
                print(f"     Progress: {progress:.0%}")
            
            return success
        else:
            return super()._execute(decision)
    
    def run_cycle(self):
        """Enhanced cycle with plan tracking"""
        super().run_cycle()
        
        if self.active_plans:
            print(f"\n   📊 Active Plans: {len(self.active_plans)}")
            for goal_id, plan in self.active_plans.items():
                progress = self._plan_progress(plan)
                print(f"      • {plan['topic']}: {progress:.0%} complete")
    
    def _print_summary(self):
        """Enhanced summary"""
        super()._print_summary()
        print(f"\n📋 Enhanced Goals:")
        print(f"   Total steps completed: {self.completed_steps}")
        print(f"   Active plans: {len(self.active_plans)}")

if __name__ == "__main__":
    print("🌀 EDEN AGENT V5 - ENHANCED GOAL SYSTEM")
    print("="*60)
    agent = EdenAgentV5()
    agent.run_continuous(cycle_seconds=30)
