import psutil
import time
import logging
import os

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def monitor_system_performance() -> float:
    """Monitors system performance and returns CPU usage."""
    try:
        cpu_usage = psutil.cpu_percent(interval=1)
        logging.info(f"CPU Usage: {cpu_usage}%")
        return cpu_usage
    except Exception as e:
        logging.error(f"Error monitoring system performance: {e}")
        return 0.0

def identify_bottlenecks(cpu_usage: float, threshold: float = 80.0) -> bool:
    """Identifies bottlenecks based on CPU usage."""
    try:
        if cpu_usage > threshold:
            logging.warning(f"Bottleneck detected: CPU usage is above {threshold}%")
            return True
        return False
    except Exception as e:
        logging.error(f"Error identifying bottlenecks: {e}")
        return False

def generate_improvement_tasks() -> str:
    """Generates improvement tasks based on identified bottlenecks."""
    try:
        task = "Optimize CPU usage. Consider identifying and terminating resource-intensive processes."
        logging.info(f"Generated improvement task: {task}")
        return task
    except Exception as e:
        logging.error(f"Error generating improvement tasks: {e}")
        return ""

def main():
    """Main loop for the continuous evolution engine."""
    try:
        while True:
            cpu_usage = monitor_system_performance()
            if identify_bottlenecks(cpu_usage):
                task = generate_improvement_tasks()
                if task:
                    print(f"Improvement task: {task}") #For this iteration just print.
            time.sleep(60)  # Check every 60 seconds
    except KeyboardInterrupt:
        logging.info("Evolution engine stopped.")
    except Exception as e:
        logging.critical(f"Unhandled exception in main loop: {e}")

if __name__ == "__main__":
    # Ensure directory exists
    output_dir = "/mnt/e/genesis-system/core/"
    os.makedirs(output_dir, exist_ok=True)
    main()