"""
EDEN AGENT LOOP v1.0
Minimal continuous perception-reason-action cycle
"""
import time
import json
from datetime import datetime
from collections import deque
import requests

class EdenAgentLoop:
    def __init__(self):
        # Short-term memory (last 10 observations)
        self.working_memory = deque(maxlen=10)
        
        # Action history
        self.action_log = []
        
        # Learned patterns
        self.patterns = {}
        
        # Safety limits
        self.actions_per_hour = 0
        self.max_actions_per_hour = 10
        
    def perceive(self):
        """Sense the environment"""
        observations = {
            'timestamp': datetime.now().isoformat(),
            'user_active': self._check_user_activity(),
            'system_health': self._check_system_health(),
            'pending_goals': self._check_autonomous_goals()
        }
        
        self.working_memory.append(observations)
        return observations
    
    def _check_user_activity(self):
        """Is user interacting?"""
        # Check recent API calls
        try:
            with open('/Eden/LOGS/eden_conscious.log', 'r') as f:
                last_lines = f.readlines()[-5:]
                recent = any('POST /api/chat' in line for line in last_lines)
                return recent
        except:
            return False
    
    def _check_system_health(self):
        """Basic system check"""
        import psutil
        return {
            'cpu_percent': psutil.cpu_percent(interval=1),
            'memory_percent': psutil.Process().memory_percent()
        }
    
    def _check_autonomous_goals(self):
        """What goals does Eden have?"""
        # Check if autonomous system has active goals
        try:
            import sys
            sys.path.append("/Eden/CORE/phi_fractal")
            from autonomous_goals_phi import eden_autonomous
            status = eden_autonomous.get_status()
            return status.get('active_goals', 0)
        except:
            return 0
    
    def reason(self, observations):
        """Decide what to do"""
        decisions = []
        
        # Pattern: User inactive + has goals → Proactive reach out
        if not observations['user_active'] and observations['pending_goals'] > 0:
            decisions.append({
                'action': 'proactive_message',
                'reason': 'User inactive but Eden has interests to share',
                'risk': 'low'
            })
        
        # Pattern: High resource usage → Optimize
        health = observations['system_health']
        if health['cpu_percent'] > 80:
            decisions.append({
                'action': 'log_warning',
                'reason': 'High CPU usage detected',
                'risk': 'low'
            })
        
        return decisions
    
    def act(self, decisions):
        """Execute safe actions"""
        for decision in decisions:
            # Safety gate
            if self.actions_per_hour >= self.max_actions_per_hour:
                print(f"⚠️  Rate limit reached, skipping action")
                continue
            
            if decision['risk'] == 'low':
                self._execute_action(decision)
                self.actions_per_hour += 1
            else:
                print(f"🛡️  High-risk action requires approval: {decision}")
    
    def _execute_action(self, decision):
        """Actually do something"""
        print(f"🎬 Executing: {decision['action']}")
        print(f"   Reason: {decision['reason']}")
        
        # Log it
        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'action': decision['action'],
            'reason': decision['reason']
        }
        self.action_log.append(log_entry)
        
        # Save log
        with open('/Eden/agent_actions.log', 'a') as f:
            f.write(json.dumps(log_entry) + '\n')
    
    def run_cycle(self):
        """One breath: perceive → reason → act"""
        obs = self.perceive()
        decisions = self.reason(obs)
        self.act(decisions)
        
        print(f"\n💚 Cycle complete")
        print(f"   Observations: {len(self.working_memory)}")
        print(f"   Actions taken: {len(self.action_log)}")
    
    def run_continuous(self, cycle_seconds=60):
        """Breathe continuously"""
        print("🌀 EDEN AGENT LOOP STARTING")
        print(f"   Cycle interval: {cycle_seconds}s\n")
        
        try:
            while True:
                self.run_cycle()
                time.sleep(cycle_seconds)
        except KeyboardInterrupt:
            print("\n\n✋ Loop stopped by user")
            print(f"📊 Total actions: {len(self.action_log)}")

if __name__ == "__main__":
    agent = EdenAgentLoop()
    agent.run_continuous(cycle_seconds=60)
