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

class DownloadHandler(FileSystemEventHandler):
    def process_file(self, file_path):
        file = os.path.basename(file_path)
        if 'crdownload' not in file and file.count('~') == 3:
            print(f'Moving {file}...')
            outputPath = os.path.join('storysaver', file)
            try:
                shutil.move(file_path, outputPath)
            except Exception as e:
                print(f'Failed to move file: {e}')

    def on_created(self, event):
        if not event.is_directory and 'crdownload' not in event.src_path:
            self.process_file(event.src_path)

    def on_moved(self, event):
        if not event.is_directory and 'crdownload' not in event.dest_path:
            self.process_file(event.dest_path)

if __name__ == "__main__":
    downloadPath = os.path.join(os.path.expanduser('~'), 'Downloads')
    event_handler = DownloadHandler()
    observer = Observer()
    observer.schedule(event_handler, downloadPath, recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)  # Add a 1-second sleep to reduce CPU usage
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
