import time
import requests
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

TOKEN = "13e1bb01-9fd5-44a8-8ce9-4ee27133d340"
UPLOAD_URL = "https://msgs.buzalka.cz/upload-dropbox"
SOURCE_DIR = Path(r"C:\Users\vbuzalka\OneDrive - JNJ\##JNJPrenos")


def upload_file(f: Path):
    time.sleep(2)
    if not f.exists() or not f.is_file():
        return
    try:
        with f.open("rb") as fh:
            resp = requests.post(
                UPLOAD_URL,
                headers={"Authorization": f"Bearer {TOKEN}"},
                files={"file": (f.name, fh, "application/octet-stream")},
                timeout=120,
            )
        resp.raise_for_status()
        print(f"  UPLOADED | {f.name}")
        f.unlink()
    except Exception as e:
        print(f"  CHYBA   | {f.name} | {e}")


class NewFileHandler(FileSystemEventHandler):
    def on_created(self, event):
        if event.is_directory:
            return
        upload_file(Path(event.src_path))

    def on_moved(self, event):
        if event.is_directory:
            return
        upload_file(Path(event.dest_path))


if __name__ == "__main__":
    # Při startu odešli soubory, které už tam jsou
    for f in SOURCE_DIR.iterdir():
        if f.is_file():
            upload_file(f)

    observer = Observer()
    observer.schedule(NewFileHandler(), str(SOURCE_DIR), recursive=False)
    observer.start()
    print(f"Hlídám: {SOURCE_DIR}")

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