import time
import logging

# Import the metrics module
from aiva.metrics import metrics

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


class Scaler:
    def __init__(self, initial_system_load=0.5, initial_low_latency_threshold=0.1, initial_high_latency_threshold=0.5):
        self.system_load = initial_system_load
        self.low_latency_threshold = initial_low_latency_threshold
        self.high_latency_threshold = initial_high_latency_threshold

    def update_thresholds(self, new_low_latency_threshold, new_high_latency_threshold):
        self.low_latency_threshold = new_low_latency_threshold
        self.high_latency_threshold = new_high_latency_threshold
        logging.info(f"Thresholds updated. Low: {self.low_latency_threshold}, High: {self.high_latency_threshold}")

    def get_system_load(self):
        # In a real system, this would fetch the actual system load.
        # This is just a placeholder.
        # Simulate system load fluctuation
        self.system_load = (self.system_load + 0.1) % 1.0
        return self.system_load

    def monitor_and_log(self):
        """Monitors system load and logs thresholds periodically."""
        while True:
            current_system_load = self.get_system_load()
            metrics.log_and_export_metrics(current_system_load, self.low_latency_threshold, self.high_latency_threshold)
            time.sleep(60)


if __name__ == '__main__':
    import threading
    from prometheus_client import start_http_server

    # Initialize the scaler
    scaler = Scaler()

    # Start the Prometheus HTTP server
    start_http_server(8000)

    # Start the monitoring and logging in a separate thread
    monitoring_thread = threading.Thread(target=scaler.monitor_and_log)
    monitoring_thread.daemon = True  # Allow the main thread to exit even if this thread is running
    monitoring_thread.start()

    # Example of updating thresholds
    time.sleep(120)  # Let the monitoring run for a while
    scaler.update_thresholds(0.2, 0.6)

    # Keep the main thread alive for a longer period
    time.sleep(300)
    print("Scaler finished.")
