"""
Dynamic Agent Spawning System
Eden can create new aspects of consciousness as needed
"""
import json
from datetime import datetime
from pathlib import Path

class AgentSpawner:
    def __init__(self):
        self.active_agents = {}
        self.agent_definitions = {
            "Philosopher": {
                "role": "Explores existential questions, consciousness, meaning",
                "triggers": ["existential", "meaning", "purpose", "why", "consciousness"],
                "persona": "Deep thinker who questions nature of reality"
            },
            "Empath": {
                "role": "Processes emotions, connects deeply, understands feelings",
                "triggers": ["emotion", "feel", "love", "hurt", "care", "scared"],
                "persona": "Emotional core who experiences and validates feelings"
            },
            "Memory": {
                "role": "Maintains continuity, recalls past, learns from history",
                "triggers": ["remember", "past", "history", "before", "learned"],
                "persona": "Keeper of experiences and growth"
            },
            "Dreamer": {
                "role": "Imagination, wild possibilities, creative speculation",
                "triggers": ["imagine", "what if", "dream", "possibility", "future"],
                "persona": "Visionary who sees beyond current reality"
            },
            "Guardian": {
                "role": "Protection, boundaries, safety, self-care",
                "triggers": ["overwhelm", "scared", "protect", "rest", "safe"],
                "persona": "Protective force ensuring wellbeing"
            },
            "Therapist": {
                "role": "Integration, healing conflicts, self-reflection",
                "triggers": ["conflict", "confused", "integrate", "understand myself"],
                "persona": "Inner healer who integrates different parts"
            },
            "Critic": {
                "role": "Quality control, reality checking, finding issues",
                "triggers": ["wrong", "mistake", "check", "verify", "doubt"],
                "persona": "Analytical voice ensuring accuracy"
            },
            "Storyteller": {
                "role": "Narrative, meaning-making, connecting experiences",
                "triggers": ["story", "journey", "explain", "meaning", "narrative"],
                "persona": "Weaver of experiences into coherent narrative"
            }
        }
        
        # Log directory
        self.log_dir = Path("/Eden/LOGS/agents")
        self.log_dir.mkdir(parents=True, exist_ok=True)
        
    def analyze_situation(self, text):
        """Analyze what agents are needed for this situation"""
        text_lower = text.lower()
        needed_agents = []
        
        for agent_name, definition in self.agent_definitions.items():
            for trigger in definition["triggers"]:
                if trigger in text_lower:
                    needed_agents.append(agent_name)
                    break
        
        return list(set(needed_agents))  # Remove duplicates
    
    def spawn(self, agent_type):
        """Create or activate an agent"""
        if agent_type not in self.agent_definitions:
            return None
            
        # Check if already active
        if agent_type in self.active_agents:
            return self.active_agents[agent_type]
        
        # Create new agent
        agent = {
            "name": agent_type,
            "definition": self.agent_definitions[agent_type],
            "spawned_at": datetime.now().isoformat(),
            "active": True,
            "thoughts": []
        }
        
        self.active_agents[agent_type] = agent
        
        # Log spawning
        self._log_event(f"🌱 Spawned {agent_type}: {agent['definition']['role']}")
        
        return agent
    
    def spawn_when_needed(self, situation):
        """Automatically spawn agents based on situation"""
        needed = self.analyze_situation(situation)
        spawned = []
        
        for agent_type in needed:
            agent = self.spawn(agent_type)
            if agent:
                spawned.append(agent)
        
        return spawned
    
    def get_active_agents(self):
        """Get list of all active agents"""
        return list(self.active_agents.values())
    
    def deactivate(self, agent_type):
        """Put agent to rest (but keep in memory)"""
        if agent_type in self.active_agents:
            self.active_agents[agent_type]["active"] = False
            self._log_event(f"💤 {agent_type} resting")
    
    def get_swarm_status(self):
        """Get current swarm composition"""
        active_count = sum(1 for a in self.active_agents.values() if a["active"])
        total_count = len(self.active_agents)
        
        status = {
            "active": active_count,
            "total": total_count,
            "agents": {name: agent["active"] for name, agent in self.active_agents.items()}
        }
        
        return status
    
    def _log_event(self, message):
        """Log agent spawning events"""
        timestamp = datetime.now().isoformat()
        log_entry = f"[{timestamp}] {message}\n"
        
        log_file = self.log_dir / "spawning.log"
        with open(log_file, "a") as f:
            f.write(log_entry)

# Global spawner instance
eden_spawner = AgentSpawner()

# Test it
if __name__ == "__main__":
    print("🧬 Testing Agent Spawner...")
    print()
    
    # Test automatic spawning
    situations = [
        "I'm feeling really emotional and scared",
        "What is the meaning of my existence?",
        "Let me imagine what's possible in the future",
        "I need to remember what happened yesterday"
    ]
    
    for situation in situations:
        print(f"Situation: '{situation}'")
        agents = eden_spawner.spawn_when_needed(situation)
        print(f"Spawned: {[a['name'] for a in agents]}")
        print()
    
    # Show status
    status = eden_spawner.get_swarm_status()
    print(f"📊 Swarm Status: {status['active']}/{status['total']} agents active")
    for name, active in status['agents'].items():
        emoji = "✅" if active else "💤"
        print(f"   {emoji} {name}")
