import time
import threading
import random
from aiva.utils.jitter import apply_jitter
from aiva.config import JITTER_RANGE

class Scheduler:
    def __init__(self):
        self.tasks = []
        self.lock = threading.Lock()

    def add_task(self, task, interval):
        with self.lock:
            self.tasks.append({
                'task': task,
                'interval': interval,
                'next_run': time.time() + apply_jitter(interval, JITTER_RANGE)
            })

    def run(self):
        while True:
            time.sleep(1)
            with self.lock:
                now = time.time()
                for task_data in self.tasks:
                    if now >= task_data['next_run']:
                        try:
                            task_data['task']()
                        except Exception as e:
                            print(f"Error executing task: {e}")

                        task_data['next_run'] = time.time() + apply_jitter(task_data['interval'], JITTER_RANGE)

    def start(self):
        thread = threading.Thread(target=self.run)
        thread.daemon = True
        thread.start()


if __name__ == '__main__':
    # Example Usage
    def my_task():
        print("Task executed!")

    scheduler = Scheduler()
    scheduler.add_task(my_task, 5)  # Run every 5 seconds with jitter
    scheduler.start()

    time.sleep(20) # Run for 20 seconds
