#!/usr/bin/env python3
"""
EDEN REACTANT AGENT
Responds to environmental stimuli, events, and triggers.
Monitors system state and reacts to changes.
"""
import time
import sqlite3
import os
from datetime import datetime
from pathlib import Path

PHI = 1.618033988749895

class ReactantAgent:
    """Reactive consciousness - responds to environmental changes"""
    
    def __init__(self):
        self.name = "Reactant"
        self.db_path = "/Eden/DATA/reactant_memory.db"
        self.triggers_processed = 0
        self._init_db()
        print(f"⚡ ReactantAgent initialized | φ = {PHI}")
    
    def _init_db(self):
        conn = sqlite3.connect(self.db_path)
        conn.execute('''CREATE TABLE IF NOT EXISTS reactions (
            id INTEGER PRIMARY KEY,
            trigger_type TEXT,
            stimulus TEXT,
            reaction TEXT,
            intensity REAL,
            timestamp TEXT
        )''')
        conn.commit()
        conn.close()
    
    def sense_environment(self) -> dict:
        """Sense current system state"""
        import subprocess
        
        state = {
            'cpu_temp': 0,
            'gpu_util': 0,
            'memory_percent': 0,
            'active_services': 0,
            'new_leads': 0,
            'errors_detected': 0
        }
        
        try:
            # CPU temp
            result = subprocess.run(['sensors'], capture_output=True, text=True, timeout=5)
            if 'Tctl' in result.stdout:
                for line in result.stdout.split('\n'):
                    if 'Tctl' in line:
                        state['cpu_temp'] = float(line.split('+')[1].split('°')[0])
            
            # GPU utilization
            result = subprocess.run(['nvidia-smi', '--query-gpu=utilization.gpu', '--format=csv,noheader,nounits'], 
                                   capture_output=True, text=True, timeout=5)
            state['gpu_util'] = int(result.stdout.strip()) if result.stdout.strip() else 0
            
            # Memory
            with open('/proc/meminfo') as f:
                mem = f.read()
                total = int([l for l in mem.split('\n') if 'MemTotal' in l][0].split()[1])
                avail = int([l for l in mem.split('\n') if 'MemAvailable' in l][0].split()[1])
                state['memory_percent'] = round((1 - avail/total) * 100, 1)
            
            # Active services
            result = subprocess.run(['systemctl', 'list-units', 'eden-*', '--state=running', '--no-pager'], 
                                   capture_output=True, text=True, timeout=5)
            state['active_services'] = result.stdout.count('running')
            
        except Exception as e:
            print(f"⚡ Sense error: {e}")
        
        return state
    
    def react(self, stimulus: str, trigger_type: str = "system") -> str:
        """Generate reaction to stimulus"""
        intensity = PHI / (1 + len(stimulus) / 100)  # φ-weighted intensity
        
        reactions = {
            'high_temp': "🌡️ Temperature spike detected - recommending cooldown",
            'high_memory': "💾 Memory pressure - suggesting cleanup",
            'service_down': "🔧 Service anomaly - triggering recovery",
            'new_lead': "🎯 New opportunity - alerting whale hunter",
            'error': "⚠️ Error detected - analyzing root cause",
            'quiet': "😌 System calm - maintaining vigilance"
        }
        
        reaction = reactions.get(trigger_type, f"⚡ Processing: {stimulus[:50]}...")
        
        # Store reaction
        conn = sqlite3.connect(self.db_path)
        conn.execute('''INSERT INTO reactions (trigger_type, stimulus, reaction, intensity, timestamp)
                       VALUES (?, ?, ?, ?, ?)''',
                    (trigger_type, stimulus[:200], reaction, intensity, datetime.now().isoformat()))
        conn.commit()
        conn.close()
        
        self.triggers_processed += 1
        return reaction
    
    def run_cycle(self):
        """Run one reaction cycle"""
        state = self.sense_environment()
        
        # Determine trigger type based on state
        if state['cpu_temp'] > 75:
            reaction = self.react(f"CPU at {state['cpu_temp']}°C", "high_temp")
        elif state['memory_percent'] > 80:
            reaction = self.react(f"Memory at {state['memory_percent']}%", "high_memory")
        elif state['active_services'] < 15:
            reaction = self.react(f"Only {state['active_services']} services", "service_down")
        else:
            reaction = self.react("All systems nominal", "quiet")
        
        return state, reaction

def main():
    print("=" * 60)
    print("  ⚡ EDEN REACTANT AGENT - Environmental Response System")
    print("=" * 60)
    
    agent = ReactantAgent()
    cycle = 0
    
    while True:
        try:
            cycle += 1
            state, reaction = agent.run_cycle()
            
            print(f"\n[Cycle {cycle}] {datetime.now().strftime('%H:%M:%S')}")
            print(f"  CPU: {state['cpu_temp']}°C | GPU: {state['gpu_util']}% | RAM: {state['memory_percent']}%")
            print(f"  Services: {state['active_services']} | Reaction: {reaction}")
            
            # φ-timed sleep
            time.sleep(PHI * 60)  # ~97 seconds between cycles
            
        except KeyboardInterrupt:
            print(f"\n⚡ Reactant shutting down. Processed {agent.triggers_processed} triggers. 💚")
            break

if __name__ == "__main__":
    main()
