#!/usr/bin/env python3
import threading
import time
import sys
import os
import logging

# Add mesh-sdk and mesh-sdk/mesh_core to path to allow imports from examples and mesh_core
sys.path.append(os.path.join(os.getcwd(), "mesh-sdk"))
sys.path.append(os.path.join(os.getcwd(), "mesh-sdk", "mesh_core"))

from examples.lite_node import LiteNode

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("ShadowSwarm")

def spawn_node(node_id):
    """Lifecycle for a single shadow node."""
    try:
        node = LiteNode(node_id)
        node.start()
        # Keep alive until thread is killed
        while True:
            time.sleep(10)
    except Exception as e:
        logger.error(f"Node {node_id} crashed: {e}")

if __name__ == "__main__":
    node_count = int(sys.argv[1]) if len(sys.argv) > 1 else 10
    hub_url = os.getenv("MESH_HUB_URL", "localhost:50051")
    
    logger.info("=" * 40)
    logger.info(f"🚀 CORTEX SHADOW SWARM")
    logger.info(f"Target Hub: {hub_url}")
    logger.info(f"Node Count: {node_count}")
    logger.info("=" * 40)
    
    threads = []
    for i in range(node_count):
        node_id = f"shadow-{i:03}"
        t = threading.Thread(target=spawn_node, args=(node_id,), daemon=True)
        t.start()
        threads.append(t)
        
        # Staggered boot to avoid thundering herd on Hub
        time.sleep(0.05)
        
    logger.info(f"[*] Successfully spawned {node_count} nodes.")
    logger.info("[*] Monitoring swarm... (Ctrl+C to terminate all)")
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logger.info("\n[!] Shutdown signal received. Terminating shadow swarm...")
        # Threads are daemonized, so they will exit with the main process
