"""
scan_worker.py — QThread der scanner biblioteker i baggrunden.
Rapporterer fremgang via signals uden at blokere GUI.
"""
from PyQt6.QtCore import QThread, pyqtSignal


class ScanWorker(QThread):
    progress = pyqtSignal(int, int, str)   # done, total, filename
    finished = pyqtSignal(int, str)        # antal, library_path
    error    = pyqtSignal(str)

    def __init__(self, library_id: int, library_path: str,
                 db_path: str, overwrite_bpm: bool = False):
        super().__init__()
        self._library_id   = library_id
        self._library_path = library_path
        self._db_path      = db_path
        self._overwrite_bpm = overwrite_bpm
        self._cancelled    = False

    def cancel(self):
        self._cancelled = True
        self.requestInterruption()

    def run(self):
        try:
            from local.scanner import scan_library

            def on_progress(done, total, filename):
                if self.isInterruptionRequested():
                    raise InterruptedError()
                self.progress.emit(done, total, filename)

            count = scan_library(
                self._library_id,
                self._library_path,
                self._db_path,
                overwrite_bpm=self._overwrite_bpm,
                progress_callback=on_progress,
            )
            if not self._cancelled:
                self.finished.emit(count, self._library_path)
        except InterruptedError:
            pass
        except Exception as e:
            self.error.emit(str(e))
