"""
bpm_worker.py — QThread til BPM-analyse i baggrunden.
"""
import sqlite3
from PyQt6.QtCore import QThread, pyqtSignal


class BpmScanWorker(QThread):
    progress = pyqtSignal(int, int)   # done, total
    finished = pyqtSignal(int)        # antal analyseret

    def __init__(self, library_id: int, db_path: str,
                 scan_all: bool = False):
        super().__init__()
        self._library_id = library_id
        self._db_path    = db_path
        self._scan_all   = scan_all

    def cancel(self):
        self.requestInterruption()
        # Afbryd hurtigt ved at sætte et flag
        self._cancelled = True

    def run(self):
        import time
        self._cancelled = False
        try:
            from local.tag_reader import analyze_bpm
            conn = sqlite3.connect(self._db_path)
            conn.row_factory = sqlite3.Row

            if self._scan_all:
                songs = conn.execute(
                    "SELECT id, local_path FROM songs "
                    "WHERE library_id=? AND file_missing=0",
                    (self._library_id,)
                ).fetchall()
            else:
                songs = conn.execute(
                    "SELECT id, local_path FROM songs "
                    "WHERE library_id=? AND file_missing=0 "
                    "AND (bpm IS NULL OR bpm=0)",
                    (self._library_id,)
                ).fetchall()

            total = len(songs)
            done  = 0

            for song in songs:
                if self._cancelled or self.isInterruptionRequested():
                    break
                try:
                    bpm = analyze_bpm(song["local_path"])
                    if bpm and bpm > 0:
                        conn.execute(
                            "UPDATE songs SET bpm=? WHERE id=?",
                            (int(round(bpm)), song["id"])
                        )
                        conn.commit()
                except Exception:
                    pass
                done += 1
                self.progress.emit(done, total)
                time.sleep(0.01)  # Yield så GUI ikke hænger

            conn.close()
            self.finished.emit(done)
        except Exception as e:
            self.finished.emit(0)
