import time
import random
from aiva.loop_health import LoopHealthMonitor

class LoopController:
    def __init__(self, health_monitor: LoopHealthMonitor):
        self.health_monitor = health_monitor
        self.running = True

    def run(self):
        print("LoopController: Starting main loop...")
        while self.running:
            start_time = time.time()

            # Simulate some work being done in the loop
            self.simulate_work()

            end_time = time.time()
            iteration_time = end_time - start_time

            # Update health metrics
            self.health_monitor.update_iteration_time(iteration_time)
            self.health_monitor.update_resource_usage(random.uniform(0.1, 0.5)) # Simulate resource usage

            # Check health status
            health_score = self.health_monitor.get_health_score()
            if health_score < 0.7:
                print(f"LoopController: Health score is low: {health_score:.2f}. Triggering alert!")
                # Trigger alert mechanism here (e.g., send notification, log error)
                self.trigger_alert()

            time.sleep(0.1) # Simulate loop frequency

    def simulate_work(self):
        # Simulate some computational work with a chance of error
        if random.random() < 0.01:  # Simulate 1% error rate
            self.health_monitor.increment_error_count()
            raise Exception("Simulated error in main loop!")
        else:
            time.sleep(random.uniform(0.01, 0.05))


    def stop(self):
        print("LoopController: Stopping main loop...")
        self.running = False

    def trigger_alert(self):
        print("LoopController: Triggering alert mechanism.")
        # In a real system, this would involve sending a notification,
        # logging an error, or taking some other corrective action.
        pass

if __name__ == '__main__':
    health_monitor = LoopHealthMonitor()
    loop_controller = LoopController(health_monitor)

    try:
        loop_controller.run()
    except KeyboardInterrupt:
        print("Ctrl+C detected. Stopping loop.")
        loop_controller.stop()
    except Exception as e:
        print(f"An error occurred: {e}")
        loop_controller.stop()
