
"""
Continuous Evolution Loop
The Heartbeat of Genesis.
Runs an infinite loop of Scout -> Plan -> Evolve cycles using low-cost Gemini Flash agents.
"""

import time
import sys
import os
import signal
from datetime import datetime
import json # Added import

# Add root to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from swarms.genesis_swarm import GenesisSwarm

def is_unceasing_motion_active():
    path = "E:/genesis-system/config/unceasing_motion.json"
    if os.path.exists(path):
        with open(path, "r") as f:
            config = json.load(f)
            return config.get("unceasing_motion", False)
    return False

class EvolutionLoop:
    def __init__(self):
        self.swarm = GenesisSwarm()
        self.running = True
        
        # Handle graceful shutdown
        signal.signal(signal.SIGINT, self.shutdown)
        signal.signal(signal.SIGTERM, self.shutdown)

    def shutdown(self, signum, frame):
        print("\n\n🛑 [Loop] Shutdown signal received. Stopping...")
        self.running = False

    def start(self):
        print(f"\n🚀 [Loop] GENESIS EVOLUTION HEARTBEAT STARTED")
        print(f"   Model: Gemini 2.0 Flash Exp")
        print(f"   Budget: ${self.swarm.daily_budget}/day")
        print(f"   Press Ctrl+C to stop.\n")
        
        cycle_count = 0
        
        while self.running:
            try:
                cycle_count += 1
                cycle_start = time.time()
                
                print(f"\n=== CYCLE {cycle_count} START: {datetime.now().strftime('%H:%M:%S')} ===")
                
                # Execute the swarm cycle
                # Trigger n8n logic gate
                if is_unceasing_motion_active():
                    print("🌑 [Unceasing Motion] Night Mode Active. Prioritizing background chores.")
                    # Trigger background n8n tasks
                    self.swarm.think("unsupervised_evolution") # Assuming this is the intended call
                else:
                    self.swarm.run_evolution_cycle()
                
                # Check for nervous system triggers (Simulated for now)
                self.swarm.trigger_nervous_system("heartbeat", {"cycle": cycle_count})
                
                elapsed = time.time() - cycle_start
                print(f"=== CYCLE {cycle_count} COMPLETE ({elapsed:.2f}s) ===")
                
                # Sleep between cycles (conserving budget)
                # For aggressive evolution, sleep 60s. For maintenance, sleep 300s.
                sleep_time = 60
                print(f"💤 Sleeping {sleep_time}s...")
                time.sleep(sleep_time)
                
            except Exception as e:
                print(f"❌ [Loop] Error: {e}")
                time.sleep(60) # Backoff on error

if __name__ == "__main__":
    loop = EvolutionLoop()
    loop.start()
