"""Directory watcher for auto-signing new files."""
import logging
import time
import fnmatch
from pathlib import Path
from threading import Thread

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileCreatedEvent

logger = logging.getLogger("tectravision_sdk.watcher")


class _SignHandler(FileSystemEventHandler):
    def __init__(self, client, patterns: list[str], callback=None):
        self.client = client
        self.patterns = patterns
        self.callback = callback

    def on_created(self, event):
        if event.is_directory:
            return
        path = event.src_path
        if not any(fnmatch.fnmatch(Path(path).name, p) for p in self.patterns):
            return

        time.sleep(0.5)

        try:
            ext = Path(path).suffix.lower()
            if ext in (".mp4", ".webm", ".mov"):
                result = self.client.sign_video(path)
            else:
                result = self.client.sign(path)

            logger.info("Auto-signed: %s -> record %s", path, result.get("record_id"))
            if self.callback:
                self.callback(path, result)
        except Exception as e:
            logger.error("Failed to sign %s: %s", path, e)


class DirectoryWatcher:
    """Watches a directory and auto-signs new image/video files."""

    def __init__(self, client, directory: str, callback=None, patterns=None):
        self.client = client
        self.directory = directory
        self.callback = callback
        self.patterns = patterns or ["*.jpg", "*.jpeg", "*.png", "*.mp4"]
        self._observer = Observer()
        self._thread: Thread | None = None

    def start(self):
        handler = _SignHandler(self.client, self.patterns, self.callback)
        self._observer.schedule(handler, self.directory, recursive=True)
        self._observer.start()
        logger.info("Watching %s for new files (patterns: %s)", self.directory, self.patterns)

    def stop(self):
        self._observer.stop()
        self._observer.join()

    def run_forever(self):
        """Start watching and block forever."""
        self.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            self.stop()
