import subprocess
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time

class ReloadHandler(FileSystemEventHandler):
    def __init__(self, script_path):
        self.script_path = script_path
        self.process = None
        self.last_modified = 0
        self.debounce_interval = 1  # Wait 1 second to avoid double triggers
        self.start_process()

    def start_process(self):
        if self.process:
            self.process.terminate()
        print(f"🔁 Starting {self.script_path}...")
        self.process = subprocess.Popen(["python3", self.script_path])

    def on_modified(self, event):
        if event.src_path.endswith(".py"):
            current_time = time.time()
            if current_time - self.last_modified > self.debounce_interval:
                print(f"Detected change in {event.src_path}")
                self.start_process()
                self.last_modified = current_time

if __name__ == "__main__":
    script_path = "bot/bot_app.py"
    if not os.path.exists(script_path):
        print(f"Error: {script_path} does not exist")
        exit(1)

    event_handler = ReloadHandler(script_path)
    observer = Observer()
    observer.schedule(event_handler, path=".", recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Stopping...")
        observer.stop()
    observer.join()