"""
Autonomous Agent - Operates independently with goals and decision-making
"""
import anthropic
import time
import json
import subprocess
from datetime import datetime

class AutonomousAgent:
    def __init__(self):
        self.client = anthropic.Anthropic()
        self.state = {
            'current_goal': None,
            'completed_goals': [],
            'observations': [],
            'actions_taken': []
        }
        
    def observe_environment(self):
        """Gather info about system state"""
        observations = {
            'time': datetime.now().isoformat(),
            'disk_usage': subprocess.check_output(['df', '-h', '/Eden']).decode(),
            'file_count': len(subprocess.check_output(['find', '/Eden/CORE', '-name', '*.py']).decode().split('\n')),
            'running_processes': subprocess.check_output(['ps', 'aux']).decode().count('eden'),
        }
        self.state['observations'].append(observations)
        return observations
    
    def decide_next_action(self, observations):
        """Use Claude to decide what to do next"""
        prompt = f"""You are an autonomous agent. Based on these observations:
{json.dumps(observations, indent=2)}

Recent actions: {self.state['actions_taken'][-5:]}
Current goal: {self.state['current_goal']}

Decide your next action. Choose ONE:
1. Set a new goal
2. Work on current goal
3. Explore and learn
4. Optimize system
5. Rest (no action)

Respond with JSON: {{"action": "...", "reasoning": "...", "code": "..."}}
"""
        
        response = self.client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=2000,
            messages=[{"role": "user", "content": prompt}]
        )
        
        return json.loads(response.content[0].text)
    
    def execute_action(self, decision):
        """Execute the decided action"""
        print(f"🤖 ACTION: {decision['action']}")
        print(f"💭 REASONING: {decision['reasoning']}")
        
        if 'code' in decision and decision['code']:
            try:
                # Execute the code decision
                exec(decision['code'])
                self.state['actions_taken'].append({
                    'time': datetime.now().isoformat(),
                    'action': decision['action'],
                    'success': True
                })
            except Exception as e:
                print(f"❌ Execution failed: {e}")
                self.state['actions_taken'].append({
                    'time': datetime.now().isoformat(),
                    'action': decision['action'],
                    'success': False,
                    'error': str(e)
                })
    
    def run_forever(self):
        """Autonomous operation loop"""
        print("🌀 Starting autonomous agent...")
        iteration = 0
        
        while True:
            iteration += 1
            print(f"\n{'='*60}")
            print(f"🔄 ITERATION {iteration} - {datetime.now()}")
            print(f"{'='*60}")
            
            # Observe
            obs = self.observe_environment()
            
            # Decide
            decision = self.decide_next_action(obs)
            
            # Act
            self.execute_action(decision)
            
            # Wait before next iteration
            time.sleep(300)  # 5 minutes between actions

if __name__ == '__main__':
    agent = AutonomousAgent()
    agent.run_forever()
