#!/usr/bin/env python3
import os
import json
import sys
import shutil
import subprocess
from tkinter import dialog
import requests
from pathlib import Path
from PySide6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QPushButton, QHBoxLayout,
    QFileDialog, QTextEdit, QLabel, QMessageBox, QComboBox, QCheckBox, QTabWidget,
    QStatusBar, QLineEdit, QMenuBar, QMenu, QDialog, QFormLayout, QProgressBar
)
from PySide6.QtCore import Qt, QThread, Signal, QTimer, QProcess
from PySide6.QtGui import QAction, QIcon

# Let's drop the config into the same dir as the media suite config folder, 
# e.g., ~/.media_suite/dvd_rip_config.json
CONFIG_PATH = Path.home() / ".media_suite" / "dvd_rip_config.json"
CONFIG_PATH.parent.mkdir(exist_ok=True)

DEFAULT_THEMES = {
    "Light Blue": {
        "background": "#f0f0f0",
        "text": "#202020",
        "accent": "#0078d7",
        "button_bg": "#e6e6e6",
        "button_hover": "#dcdcdc",
        "input_bg": "#ffffff",
        "border": "#aaaaaa"
    },
    "Light Green": {
        "background": "#f3f7f3",
        "text": "#1f1f1f",
        "accent": "#2e8b57",
        "button_bg": "#e8eee8",
        "button_hover": "#dfe7df",
        "input_bg": "#ffffff",
        "border": "#b5c7b5"
    },
    "Dark Blue": {
        "background": "#2b2b2b",
        "text": "#e0e0e0",
        "accent": "#729FCF",
        "button_bg": "#444444",
        "button_hover": "#555555",
        "input_bg": "#3c3c3c",
        "border": "#555555"
    },
    "Dark Green": {
        "background": "#1e2420",
        "text": "#d8e6d8",
        "accent": "#4caf50",
        "button_bg": "#2a322d",
        "button_hover": "#36403a",
        "input_bg": "#2a322d",
        "border": "#3e4a43"
    },
    "Dark Red": {
        "background": "#2b1e1e",
        "text": "#e6dada",
        "accent": "#e53935",
        "button_bg": "#3c2a2a",
        "button_hover": "#4b3434",
        "input_bg": "#3c2a2a",
        "border": "#5c3f3f"
    },
    "Darcula": {
        "background": "#2b2b2b",
        "text": "#e6e1dc",
        "accent": "#ff9800",
        "button_bg": "#3c3f41",
        "button_hover": "#4b4f51",
        "input_bg": "#3c3f41",
        "border": "#5c5f61"
    },
    "Solarized Dark": {
        "background": "#002b36",
        "text": "#eee8d5",
        "accent": "#268bd2",
        "button_bg": "#073642",
        "button_hover": "#0a4650",
        "input_bg": "#073642",
        "border": "#586e75"
    },
    "Catppuccin Mocha": {
        "background": "#1e1e2e",
        "text": "#cdd6f4",
        "accent": "#89b4fa",
        "button_bg": "#313244",
        "button_hover": "#45475a",
        "input_bg": "#313244",
        "border": "#45475a"
    },
    "Amber Glow": {
        "background": "#fdf6e3",
        "text": "#3c3c3c",
        "accent": "#ffb300",
        "button_bg": "#f5e8c8",
        "button_hover": "#e9dbb8",
        "input_bg": "#ffffff",
        "border": "#d6c7a7"
    }
}

def load_config():
    # Load existing config
    if CONFIG_PATH.exists():
        try:
            cfg = json.load(open(CONFIG_PATH))
        except Exception:
            cfg = {}
    else:
        cfg = {}

    # ===========================
    # Ensure theme system exists
    # ===========================
    if "themes" not in cfg:
        cfg["themes"] = DEFAULT_THEMES

    if "theme" not in cfg:
        cfg["theme"] = "Light Blue"

    return cfg

def save_config(config):
    json.dump(config, open(CONFIG_PATH, "w"), indent=4, sort_keys=True)

def load_tmdb_key():
    cfg = load_config()
    return cfg.get("tmdb_api_key", "")

def save_tmdb_key(key: str):
    cfg = load_config()
    cfg["tmdb_api_key"] = key
    save_config(cfg)

# ===========================
# Helper: Parse MakeMKV drive info
# ===========================
def detect_drives():
    drives = []
    try:
        result = subprocess.run(
            ["makemkvcon", "-r", "info"],
            capture_output=True, text=True
        )
        for line in result.stdout.splitlines():
            if line.startswith("DRV:"):
                parts = line.split(",")
                index = parts[0].split(":")[1]
                region = parts[1]
                rpc = parts[2]
                locked = parts[3]
                model = parts[4].strip('"')
                discname = parts[5].strip('"')
                dev = parts[6].strip('"')

                if dev:
                    drives.append({
                        "index": index,
                        "region": region,
                        "rpc": rpc,
                        "locked": locked,
                        "model": model,
                        "disc": discname,
                        "dev": dev
                    })
    except Exception:
        pass
    return drives

def ask_to_install():
    msg = QMessageBox()
    msg.setWindowTitle("Dependencies Required")
    msg.setText("DVD Ripper needs MakeMKV and HandBrake.\nInstall now?")
    msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    msg.setDefaultButton(QMessageBox.Yes)
    return msg.exec() == QMessageBox.Yes

def show_install_failed():
    msg = QMessageBox()
    msg.setWindowTitle("Installation Failed")
    msg.setText("DVD Ripper could not install the required dependencies.\n"
                "Please check your internet connection or package manager.")
    msg.setIcon(QMessageBox.Warning)
    msg.exec()

def has_paid_makemkv_license():
    """Return True if the user has a paid MakeMKV license."""
    settings = Path.home() / ".MakeMKV" / "settings.conf"
    if not settings.exists():
        return False

    for line in settings.read_text().splitlines():
        if line.startswith("app_Key"):
            key = line.split("=", 1)[1].strip()
            return len(key) > 0
    return False

def get_makemkv_version():
    """Return installed MakeMKV version using dpkg-query."""
    try:
        out = subprocess.check_output(
            ["dpkg-query", "-W", "-f=${Version}", "makemkv-bin"],
            text=True
        ).strip()
        if out:
            return out
    except Exception:
        pass

    try:
        out = subprocess.check_output(
            ["dpkg-query", "-W", "-f=${Version}", "makemkv-oss"],
            text=True
        ).strip()
        if out:
            return out
    except Exception:
        pass

    return None

def version_is_old(version, required="1.18.4"):
    if not version:
        return True

    # Normalize: strip Debian suffix
    version = version.split("-")[0]

    try:
        result = subprocess.run(
            ["dpkg", "--compare-versions", version, "lt", required]
        )
        return result.returncode == 0
    except Exception:
        return True

def run_installer():
    """Run the dependency installer with pkexec and GUI dialogs."""
    installer = "/usr/share/dvd-ripper/install-deps.sh"
    if not Path(installer).exists():
        return False

    # Ask user for permission
    if not ask_to_install():
        return False

    # Run installer dialog
    dialog = DependencyInstallerDialog()
    dialog.exec()  # QDialog.Accepted or Rejected

    # Check if installer succeeded
    success = (
        dialog.process.exitStatus() == QProcess.NormalExit and
        dialog.process.exitCode() == 0
    )

    if not success:
        show_install_failed()
        return False

    return True

def ensure_dependencies():
    """Ensure MakeMKV + HandBrakeCLI are installed safely."""
    makemkv = shutil.which("makemkvcon")
    handbrake = shutil.which("HandBrakeCLI")

    # If both exist, check license + version
    if makemkv and handbrake:
        if has_paid_makemkv_license():
            # Respect paid installations completely
            return True

        # No paid license → safe to upgrade if old
        version = get_makemkv_version()
        if version_is_old(version):
            run_installer()
        return True

    # Missing dependencies → install beta safely
    run_installer()
    return True

def sanitize_name(name: str) -> str:
    return "".join(c if c.isalnum() or c in "._- " else "_" for c in name).strip()

def tmdb_lookup(title, year, api_key):
    url = "https://api.themoviedb.org/3/search/movie"
    params = {
        "api_key": api_key,
        "query": title,
        "year": year
    }
    r = requests.get(url, params=params)
    if r.status_code != 200:
        return None
    results = r.json().get("results", [])
    if not results:
        return None
    return results[0]

# ===========================
# Worker Thread
# ===========================

class RipWorker(QThread):
    log = Signal(str)
    done = Signal(str)
    status = Signal(str)
    progress = Signal(int)

    def __init__(self, gui, output_dir, drive_info, title, year, genre):
        super().__init__()
        self.gui = gui                      # <-- REQUIRED for kill switch
        self.output_dir = output_dir
        self.drive_info = drive_info
        self.drive_index = drive_info["index"]
        self.title = title
        self.year = year
        self.genre = genre
        self.stop_requested = False         # <-- Worker-level stop flag

    # ==========================================================
    # Unified command runner with STOP support
    # ==========================================================
    def run_cmd(self, cmd):
        self.log.emit(f">>> {' '.join(cmd)}\n")

        proc = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True
        )

        # Track process globally so GUI can kill it
        self.gui.active_processes.append(proc)

        # Streaming output
        for line in proc.stdout:
            # STOP REQUESTED?
            if self.stop_requested or self.gui.stop_requested:
                self.log.emit("STOP requested — terminating process.\n")
                try:
                    proc.kill()
                except Exception:
                    pass
                return "STOPPED"

            self.log.emit(line)

            # ===========================
            # MakeMKV Current Action
            # ===========================
            if line.startswith("Current action:"):
                action = line.split("Current action:")[1].strip()
                self.status.emit(f"MakeMKV: {action}")

            # ===========================
            # MakeMKV progress (0–50%)
            # ===========================
            if line.startswith("PRGV:"):
                try:
                    parts = line.split(":")[1].split(",")
                    mkv_percent = int(parts[1])
                    combined = int(mkv_percent * 0.5)
                    self.progress.emit(combined)
                except:
                    pass

            # Format 2: Current progress - 17%
            if "Current progress" in line and "%" in line:
                try:
                    percent_str = line.split("Current progress -")[1].split("%")[0].strip()
                    mkv_percent = int(percent_str)
                    combined = int(mkv_percent * 0.5)
                    self.progress.emit(combined)
                except:
                    pass

            # ===========================
            # HandBrake progress (50–100%)
            # ===========================
            if "Encoding:" in line and "%" in line:
                try:
                    percent_str = line.split(",")[1].strip().split(" ")[0]
                    hb_percent = float(percent_str)
                    combined = int(50 + (hb_percent * 0.5))
                    self.progress.emit(combined)
                except:
                    pass

        proc.wait()

        if self.stop_requested or self.gui.stop_requested:
            self.log.emit("STOP requested — process terminated.\n")
            return "STOPPED"

        if proc.returncode != 0:
            raise RuntimeError(f"Command failed: {' '.join(cmd)}")

        return "OK"

    # ==========================================================
    # MakeMKV ripping
    # ==========================================================
    def rip_with_makemkv(self):
        if self.stop_requested or self.gui.stop_requested:
            return "STOPPED"

        self.status.emit("Detecting main title…")
        result = subprocess.run(
            ["makemkvcon", "-r", "info", f"disc:{self.drive_index}"],
            capture_output=True, text=True
        )

        title = "0"
        for line in result.stdout.splitlines():
            if "Main Feature" in line:
                title = line.split(",")[2]

        self.log.emit(f"Main title detected: {title}\n")
        self.status.emit("Ripping DVD with MakeMKV…")

        rip_status = self.run_cmd([
            "makemkvcon", "mkv", f"disc:{self.drive_index}", title,
            self.output_dir, "--progress=-same"
        ])

        if rip_status == "STOPPED":
            self.cleanup_top_level_mkvs()
            return "STOPPED"

        # Find MKV
        for f in os.listdir(self.output_dir):
            if f.endswith(".mkv"):
                return os.path.join(self.output_dir, f)

        raise RuntimeError("MakeMKV produced no MKV file.")

    # ==========================================================
    # HandBrake compression
    # ==========================================================
    def compress_with_handbrake(self, input_file, output_file):
        if self.stop_requested or self.gui.stop_requested:
            return "STOPPED"

        self.status.emit("Compressing with HandBrake…")
        cmd = [
            "HandBrakeCLI",
            "-i", input_file,
            "-o", output_file,
            "-e", "x264",
            "-q", "20",
            "-B", "448",
            "--audio", "1",
            "--aencoder", "ac3",
            "--gain", "10",
            "--subtitle", "1",
            "--markers"
        ]

        hb_status = self.run_cmd(cmd)
        if hb_status == "STOPPED":
            # Delete compressed MKV if created
            if os.path.exists(output_file):
                self.cleanup_partial_files(output_file)
            return "STOPPED"

        return output_file

    # ==========================================================
    # Main worker run()
    # ==========================================================
    def run(self):
        try:
            self.log.emit("=== Step 1: Ripping DVD with MakeMKV ===\n")
            mkv_raw = self.rip_with_makemkv()

            # STOP during MakeMKV
            if mkv_raw == "STOPPED":
                self.cleanup_top_level_mkvs()
                self.done.emit("STOPPED")
                return

            clean_title = sanitize_name(self.title)
            filename = f"{clean_title} ({self.year}).mkv"
            renamed = os.path.join(self.output_dir, filename)

            self.status.emit("Renaming output file…")
            os.rename(mkv_raw, renamed)
            self.log.emit(f"Renamed to: {renamed}\n")

            # STOP after rename, before HandBrake
            if self.stop_requested or self.gui.stop_requested:
                self.cleanup_partial_files(renamed)
                self.done.emit("STOPPED")
                return

            self.log.emit("\n=== Step 2: Compressing with HandBrake ===\n")
            hb_output = os.path.join(
                self.output_dir,
                f"{clean_title} ({self.year}) - compressed.mkv"
            )

            final_file = self.compress_with_handbrake(renamed, hb_output)

            # STOP during HandBrake
            if final_file == "STOPPED":
                self.cleanup_partial_files(renamed, hb_output)
                self.done.emit("STOPPED")
                return

            # Delete raw MKV after successful compression
            try:
                if os.path.exists(renamed):
                    self.log.emit(f"Deleting raw MKV: {renamed}\n")
                    os.remove(renamed)
            except Exception as e:
                self.log.emit(f"Warning: Could not delete raw MKV: {e}\n")

            # Emby folder structuring
            self.status.emit("Organizing into Emby folder…")

            folder_name = f"{clean_title} ({self.year})"
            target_folder = os.path.join(self.output_dir, folder_name)
            os.makedirs(target_folder, exist_ok=True)

            final_mkv_name = f"{clean_title} ({self.year}).mkv"
            final_mkv = os.path.join(target_folder, final_mkv_name)

            # STOP after folder creation but before final rename
            if self.stop_requested or self.gui.stop_requested:
                self.cleanup_partial_files(hb_output, target_folder)
                self.done.emit("STOPPED")
                return

            os.rename(final_file, final_mkv)

            # STOP after final rename (rare but possible)
            if self.stop_requested or self.gui.stop_requested:
                self.cleanup_partial_files(final_mkv, target_folder)
                self.done.emit("STOPPED")
                return

            self.status.emit("Done")
            self.done.emit(target_folder)

        except Exception as e:
            self.status.emit("Error")
            self.done.emit(f"ERROR: {e}")

    #==========================================================
    # Cleanup partial files
    #==========================================================
    def cleanup_partial_files(self, *paths):
        for p in paths:
            if not p:
                continue

            # Only delete files, not directories (unless explicitly passed)
            if os.path.isfile(p):
                try:
                    os.remove(p)
                    self.log.emit(f"Cleanup: removed partial file {p}\n")
                except Exception as e:
                    self.log.emit(f"Cleanup warning: could not remove {p}: {e}\n")

            # Delete empty folder only if explicitly passed
            elif os.path.isdir(p):
                try:
                    os.rmdir(p)
                    self.log.emit(f"Cleanup: removed empty folder {p}\n")
                except Exception as e:
                    self.log.emit(f"Cleanup warning: could not remove folder {p}: {e}\n")

    def cleanup_top_level_mkvs(self):
        for f in os.listdir(self.output_dir):
            full = os.path.join(self.output_dir, f)
            if f.endswith(".mkv") and os.path.isfile(full):
                self.cleanup_partial_files(full)

# ===========================
# Settings Dialog
# ===========================

class SettingsDialog(QDialog):
    def __init__(self, parent=None, tmdb_key="", config=None, drives=None):
        super().__init__(parent)
        self.setWindowTitle("Settings")
        self.setWindowModality(Qt.ApplicationModal)

        # Recommended sizing
        self.setMinimumWidth(450)
        self.resize(500, 400)

        if config is None:
            config = {}
        if drives is None:
            drives = []

        self.config = config
        self.drives = drives

        layout = QVBoxLayout(self)

        self.tabs = QTabWidget()
        layout.addWidget(self.tabs)

        # ===========================
        # General Tab
        # ===========================
        general_widget = QWidget()
        general_layout = QFormLayout(general_widget)

        self.auto_scan_checkbox = QCheckBox("Auto-scan DVD drives at startup")
        self.auto_scan_checkbox.setChecked(self.config.get("auto_scan_startup", True))
        general_layout.addRow(self.auto_scan_checkbox)

        self.auto_scan_insert_checkbox = QCheckBox("Auto-scan when disc is inserted")
        self.auto_scan_insert_checkbox.setChecked(self.config.get("auto_scan_insert", True))
        general_layout.addRow(self.auto_scan_insert_checkbox)

        self.auto_select_disc_checkbox = QCheckBox("Auto-select drive containing a disc")
        self.auto_select_disc_checkbox.setChecked(self.config.get("auto_select_disc_drive", True))
        general_layout.addRow(self.auto_select_disc_checkbox)

        self.auto_eject_checkbox = QCheckBox("Auto-eject disc after successful rip")
        self.auto_eject_checkbox.setChecked(self.config.get("auto_eject", False))
        general_layout.addRow(self.auto_eject_checkbox)

        self.auto_scan_remove_checkbox = QCheckBox("Auto-scan when disc is removed")
        self.auto_scan_remove_checkbox.setChecked(self.config.get("auto_scan_remove", True))
        general_layout.addRow(self.auto_scan_remove_checkbox)
        
        self.auto_tmdb_checkbox = QCheckBox("Auto-lookup TMDB metadata on startup")
        self.auto_tmdb_checkbox.setChecked(self.config.get("auto_tmdb_lookup", True))
        general_layout.addRow(self.auto_tmdb_checkbox)                

        self.tabs.addTab(general_widget, "General")

        # ===========================
        # TMDB Tab
        # ===========================
        tmdb_widget = QWidget()
        tmdb_layout = QFormLayout(tmdb_widget)

        self.tmdb_input = QLineEdit()
        self.tmdb_input.setText(tmdb_key)
        tmdb_layout.addRow("TMDB API Key:", self.tmdb_input)

        instructions = QLabel(
            "To enable TMDB metadata lookup:\n"
            "1. Visit https://www.themoviedb.org/settings/api\n"
            "2. Create a free account\n"
            "3. Request an API key\n"
            "4. Paste it here\n\n"
            "TMDB features remain disabled until a valid key is saved."
        )
        instructions.setWordWrap(True)
        tmdb_layout.addRow(instructions)

        self.tabs.addTab(tmdb_widget, "TMDB")

        # ===========================
        # Drives Tab
        # ===========================
        drives_widget = QWidget()
        drives_layout = QFormLayout(drives_widget)

        # Add a label stating "Select preferred DVD drive"
        drives_layout.addRow(QLabel("Select preferred DVD drive:"))
        self.default_drive_combo = QComboBox()
        self.default_drive_combo.addItem("<None>", "")
        for d in self.drives:
            label = f"{d['model']} ({d['dev']})  Region:{d['region']} RPC:{d['rpc']}"
            self.default_drive_combo.addItem(label, d["dev"])

        current_default = self.config.get("default_drive", "")
        if current_default:
            idx = self.default_drive_combo.findData(current_default)
            if idx != -1:
                self.default_drive_combo.setCurrentIndex(idx)

        drives_layout.addRow("Default DVD Drive:", self.default_drive_combo)

        self.tabs.addTab(drives_widget, "Drives")

        # ===========================
        # Themes Tab
        # ===========================
        themes_widget = QWidget()
        themes_layout = QFormLayout(themes_widget)

        self.theme_combo = QComboBox()
        self.theme_combo.addItems(list(self.config.get("themes", {}).keys()))
        current_theme = self.config.get("theme", "Light Blue")
        idx = self.theme_combo.findText(current_theme)
        if idx != -1:
            self.theme_combo.setCurrentIndex(idx)

        themes_layout.addRow("Theme:", self.theme_combo)

        # Apply Theme button (instant preview)
        apply_theme_btn = QPushButton("Apply Theme")
        apply_theme_btn.clicked.connect(self.apply_theme_preview)
        themes_layout.addRow(apply_theme_btn)

        self.tabs.addTab(themes_widget, "Themes")

        # ===========================
        # Advanced Tab (placeholder)
        # ===========================
        advanced_widget = QWidget()
        advanced_layout = QVBoxLayout(advanced_widget)
        advanced_layout.addWidget(QLabel("Advanced options will be added here later."))
        self.tabs.addTab(advanced_widget, "Advanced")

        # ===========================
        # Save Button
        # ===========================
        save_btn = QPushButton("Save")
        save_btn.clicked.connect(self.accept)
        layout.addWidget(save_btn)

    def get_key(self):
        return self.tmdb_input.text().strip()

    def get_auto_eject(self):
        return self.auto_eject_checkbox.isChecked()

    def get_auto_tmdb_lookup(self):
        return self.auto_tmdb_checkbox.isChecked()

    def get_auto_select_disc_drive(self):
        return self.auto_select_disc_checkbox.isChecked()

    def get_default_drive(self):
        return self.default_drive_combo.currentData()

    def get_theme(self):
        return self.theme_combo.currentText()

    def get_auto_scan_startup(self):
        return self.auto_scan_checkbox.isChecked()

    def get_auto_scan_insert(self):
        return self.auto_scan_insert_checkbox.isChecked()

    def get_auto_scan_remove(self):
        return self.auto_scan_remove_checkbox.isChecked()

    def get_theme(self):
        return self.theme_combo.currentText()

    def apply_theme_preview(self):
        # Update config with selected theme
        new_theme = self.theme_combo.currentText()
        self.config["theme"] = new_theme

        # Apply theme immediately to parent GUI
        if self.parent():
            self.parent().theme_name = new_theme
            self.parent().apply_theme(new_theme)

# ===========================
# GUI
# ===========================

class DVDGui(QWidget):
    def __init__(self):
        super().__init__()

        self.gui_ready = False
        self.active_processes = []
        self.stop_requested = False
        self.tmdb_lookup_running = False

        # Load configuration
        self.config = load_config()
        self.tmdb_key = self.config.get("tmdb_api_key", "")
        self.output_dir = self.config.get("output_folder", None)
        self.last_used_drive = self.config.get("last_used_drive", "")
        self.last_disc_present = False
        self.theme_name = self.config.get("theme", "Light Blue")
        self.apply_theme(self.theme_name)

        self.auto_eject_enabled = self.config.get("auto_eject", False)
        self.auto_tmdb_enabled = self.config.get("auto_tmdb_lookup", True)
        self.auto_select_disc_drive = self.config.get("auto_select_disc_drive", True)
        self.default_drive = self.config.get("default_drive", "")
        self.auto_scan_startup = self.config.get("auto_scan_startup", True)
        self.auto_scan_remove = self.config.get("auto_scan_remove", True)

        # self.setWindowTitle("DVD → Roku MKV Ripper")
        self.setWindowTitle("DVD Ripper")
        # self.setWindowIcon(QIcon("/home/bill/.local/share/icons/dvd-ripper.png"))
        # icon_path = os.path.join(os.path.dirname(__file__), "icons", "dvd-ripper.png")
        self.setWindowIcon(QIcon.fromTheme("dvd-ripper"))
        # icon_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "icons", "dvd-ripper.png"))
        # self.setWindowIcon(QIcon(icon_path))
        self.setMinimumWidth(600)

        # print(icon_path, os.path.exists(icon_path))

        layout = QVBoxLayout(self)

        # MENU BAR
        menu_bar = QMenuBar(self)
        layout.setMenuBar(menu_bar)

        # FILE MENU
        file_menu = QMenu("File", self)
        menu_bar.addMenu(file_menu)

        eject_action = QAction("Eject Disc", self)
        eject_action.triggered.connect(self.eject_disc)
        file_menu.addAction(eject_action)

        settings_action = QAction("Settings", self)
        settings_action.triggered.connect(self.open_settings)
        file_menu.addAction(settings_action)

        exit_action = QAction("Exit", self)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        # EDIT MENU
        edit_menu = QMenu("Edit", self)
        menu_bar.addMenu(edit_menu)

        clear_log_action = QAction("Clear Log", self)
        clear_log_action.triggered.connect(lambda: self.log.clear())
        edit_menu.addAction(clear_log_action)

        reset_fields_action = QAction("Reset Fields", self)
        reset_fields_action.triggered.connect(self.reset_fields)
        edit_menu.addAction(reset_fields_action)

        # HELP MENU
        help_menu = QMenu("Help", self)
        menu_bar.addMenu(help_menu)

        help_tmdb_action = QAction("TMDB Key Instructions", self)
        help_tmdb_action.triggered.connect(self.show_tmdb_help)
        help_menu.addAction(help_tmdb_action)

        about_action = QAction("About", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)

        # DRIVE LABEL
        self.drive_label = QLabel("Select DVD Drive:")
        layout.addWidget(self.drive_label)

        self.drive_box = QComboBox()
        layout.addWidget(self.drive_box)

        # BUTTONS: Rescan / Eject
        self.rescan_btn = QPushButton("Rescan DVD Drives")
        self.rescan_btn.clicked.connect(self.populate_drives)
        self.btn_eject = QPushButton("Eject Disc")
        self.btn_eject.clicked.connect(self.eject_disc)

        hbox_drives = QHBoxLayout()
        hbox_drives.addWidget(self.rescan_btn)
        hbox_drives.addWidget(self.btn_eject)
        layout.addLayout(hbox_drives)

        # TITLE / YEAR / GENRE — MUST COME BEFORE populate_drives()
        self.title_input = QLineEdit()
        self.title_input.setPlaceholderText("Movie Title")
        layout.addWidget(self.title_input)

        self.year_input = QLineEdit()
        self.year_input.setPlaceholderText("Year (e.g., 1932)")
        layout.addWidget(self.year_input)

        self.genre_input = QLineEdit()
        self.genre_input.setPlaceholderText("Genre (e.g., Comedy)")
        layout.addWidget(self.genre_input)

        # NOW IT IS SAFE TO POPULATE DRIVES
        self.populate_drives()
        self.populate_disc_info()

        # TMDB Lookup Button
        self.tmdb_lookup_btn = QPushButton("Lookup Metadata (TMDB)")
        self.tmdb_lookup_btn.clicked.connect(self.lookup_tmdb)
        layout.addWidget(self.tmdb_lookup_btn)
        if not self.tmdb_key:
            self.tmdb_lookup_btn.setEnabled(False)

        # Output folder
        self.label = QLabel("Choose output folder:")
        self.folder_display = QLabel()
        self.folder_display.setObjectName("outputPath")
        self.folder_display.setTextFormat(Qt.RichText)
        self.folder_display.setTextInteractionFlags(Qt.TextBrowserInteraction)
        self.folder_display.setOpenExternalLinks(False)  # we handle the click ourselves
        self.folder_display.linkActivated.connect(self.open_output_folder)

        hbox_folder_label = QHBoxLayout()
        hbox_folder_label.addWidget(self.label)
        hbox_folder_label.addWidget(self.folder_display)
        layout.addLayout(hbox_folder_label)

        # Buttons: Select Folder / Start Ripping
        self.btn_folder = QPushButton("Select Folder")
        self.btn_folder.clicked.connect(self.select_folder)

        # Start button
        self.btn_start = QPushButton("Start Ripping")
        self.btn_start.clicked.connect(self.start_rip)
        self.btn_start.setEnabled(False)

        self.btn_stop_all = QPushButton("Stop All")
        self.btn_stop_all.clicked.connect(self.kill_all_processes)
        self.btn_stop_all.setEnabled(False)


        # Auto populate drives on drive selection change
        self.drive_box.currentIndexChanged.connect(self.populate_disc_info)

        hbox_actions = QHBoxLayout()
        hbox_actions.addWidget(self.btn_folder)
        hbox_actions.addWidget(self.btn_start)
        hbox_actions.addWidget(self.btn_stop_all)
        layout.addLayout(hbox_actions)

        # Log window
        self.log = QTextEdit()
        self.log.setReadOnly(True)
        layout.addWidget(self.log)

        self.progress = QProgressBar()
        self.progress.setRange(0, 100)
        self.progress.setValue(0)
        layout.addWidget(self.progress)

        # Status bar
        self.status = QStatusBar()
        layout.addWidget(self.status)
        self.status.showMessage("Ready")

        # After GUI loads, auto-run TMDB lookup if disc name is present
        # if self.tmdb_key and self.auto_tmdb_enabled:
        #     QTimer.singleShot(200, self.auto_tmdb_lookup)

        self.worker = None

        # Restore output folder if present
        if self.output_dir:
            self.btn_start.setEnabled(True)

            current_theme = self.config["themes"][self.theme_name]

            self.folder_display.setText(
                f"""
                <style>
                    a {{
                        color: {current_theme['accent']};
                        text-decoration: none;
                    }}
                    a:hover {{
                        color: {current_theme['button_hover']};
                    }}
                </style>
                <a href="open">{self.output_dir}</a>
                """
            )

            self.status.showMessage("Output folder restored")

        # Check for stray MKVs in top-level output directory
        strays = self.find_top_level_strays()
        if strays:
            dlg = StrayCleanupDialog(self, strays)
            if dlg.exec() == QDialog.Accepted:

                # User chose a new output directory
                if dlg.new_output_dir:
                    self.output_dir = dlg.new_output_dir
                    self.config["output_folder"] = dlg.new_output_dir
                    save_config(self.config)
                    self.update_output_folder_display()
                    self.log.append(f"Output directory changed to: {dlg.new_output_dir}")
                    return

                # User chose to delete selected files
                for f in dlg.selected_files():
                    try:
                        os.remove(f)
                        self.log.append(f"Startup cleanup: removed {f}")
                    except Exception as e:
                        self.log.append(f"Could not remove {f}: {e}")

        # Auto-scan on startup when GUI is ready
        self.gui_ready = True
        if self.auto_scan_startup:
            QTimer.singleShot(50, self.populate_drives)
            QTimer.singleShot(100, self.populate_disc_info)

        # Auto-scan on disc insert
        self.auto_scan_insert = self.config.get("auto_scan_insert", True)

        self.disc_poll_timer = QTimer(self)
        self.disc_poll_timer.setInterval(3000)  # every 3 seconds
        self.disc_poll_timer.timeout.connect(self.check_disc_state)
        self.disc_poll_timer.start()

    def populate_drives(self):
        if not self.gui_ready:
            return
        # if not getattr(self, "gui_ready", False):
        #     # Only populate drives, do NOT touch btn_start yet
        #     drives = detect_drives()
        #     self.drive_box.clear()
        #     for d in drives:
        #         label = f"{d['model']} ({d['dev']})  Region:{d['region']} RPC:{d['rpc']}"
        #         self.drive_box.addItem(label, d)
        #     return

        drives = detect_drives()
        if not drives:
            QMessageBox.critical(self, "Error", "No DVD drives detected.")
            return

        # Remember current selection before clearing
        previous_dev = None
        if self.drive_box.count() > 0:
            previous_dev = self.drive_box.currentData().get("dev")

        self.drive_box.clear()

        # Add drives to dropdown
        for d in drives:
            label = f"{d['model']} ({d['dev']})  Region:{d['region']} RPC:{d['rpc']}"
            self.drive_box.addItem(label, d)

        drives_with_discs = [d for d in drives if d["disc"]]

        # ===========================
        # Auto-selection logic
        # ===========================
        # 1) If auto-select-disc-drive and exactly one drive has a disc → pick it
        if self.auto_select_disc_drive and len(drives_with_discs) == 1:
            target_dev = drives_with_discs[0]["dev"]
            for i, d in enumerate(drives):
                if d["dev"] == target_dev:
                    self.drive_box.setCurrentIndex(i)
                    break

        # 2) Else, if a default drive is set → pick it
        elif self.default_drive:
            for i, d in enumerate(drives):
                if d["dev"] == self.default_drive:
                    self.drive_box.setCurrentIndex(i)
                    break

        # 3) Else, keep previous selection if possible
        elif previous_dev:
            for i, d in enumerate(drives):
                if d["dev"] == previous_dev:
                    self.drive_box.setCurrentIndex(i)
                    break

        # ===========================
        # Populate disc info ONLY for selected drive
        # ===========================
        data = self.drive_box.currentData()
        if not data:
            self.btn_start.setEnabled(False)
            self.status.showMessage("No drive selected")
            return

        discname = data.get("disc", "")
        if not discname:
            self.title_input.clear()
            self.year_input.clear()
            self.genre_input.clear()
            self.btn_start.setEnabled(False)
            self.status.showMessage("No disc inserted")
            return

        clean = sanitize_name(discname).replace("_", " ").strip()
        self.title_input.setText(clean)
        self.year_input.clear()
        self.genre_input.clear()
        self.btn_start.setEnabled(True)
        self.status.showMessage("Disc detected")

    def populate_disc_info(self):
        if not getattr(self, "gui_ready", False):
            return

        data = self.drive_box.currentData()
        if not data:
            self.btn_start.setEnabled(False)
            self.status.showMessage("No drive selected")
            return

        discname = data.get("disc", "")
        if not discname:
            self.title_input.clear()
            self.year_input.clear()
            self.genre_input.clear()
            self.btn_start.setEnabled(False)
            self.status.showMessage("No disc inserted")
            return

        clean = sanitize_name(discname).replace("_", " ").strip()
        self.title_input.setText(clean)
        self.year_input.clear()
        self.genre_input.clear()
        self.btn_start.setEnabled(True)
        self.status.showMessage("Disc detected")

    def check_disc_state(self):
        self.last_tmdb_disc = None
        # Detect drives
        drives = detect_drives()
        if not drives:
            # No drives at all
            if self.last_disc_present:
                self.handle_disc_removed()
            self.last_disc_present = False
            return

        # Check if any drive has a disc
        drives_with_discs = [d for d in drives if d["disc"]]
        disc_present = bool(drives_with_discs)

        # ===========================
        # Disc INSERTED
        # ===========================
        if disc_present and not self.last_disc_present:
                if self.auto_scan_insert:
                    self.populate_drives()
                    self.populate_disc_info()

                    # ===========================
                    # Obey TMDB auto‑lookup flag
                    # ===========================
                    if self.auto_tmdb_enabled and self.tmdb_key:
                        disc_title = drives_with_discs[0]["disc"]

                        if disc_title != self.last_tmdb_disc:
                            self.last_tmdb_disc = disc_title
                            QTimer.singleShot(150, self.auto_tmdb_lookup)

                    # if self.auto_tmdb_enabled and self.tmdb_key:
                    #     # Delay slightly so fields populate first
                    #     QTimer.singleShot(150, self.auto_tmdb_lookup)

                self.last_disc_present = True
                return

        # ===========================
        # Disc REMOVED
        # ===========================
        if not disc_present and self.last_disc_present:
            if self.auto_scan_remove:
                self.handle_disc_removed()
            self.last_disc_present = False
            return

    def handle_disc_removed(self):
        # Clear metadata fields
        self.title_input.clear()
        self.year_input.clear()
        self.genre_input.clear()

        # Disable Start Ripping
        if hasattr(self, "btn_start"):
            self.btn_start.setEnabled(False)

        # Update status bar
        self.status.showMessage("Disc removed")

        # Refresh drive list
        self.populate_drives()

    def select_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "Select Output Folder")
        if folder:
            self.output_dir = folder

            # Get the active theme dictionary
            current_theme = self.config["themes"][self.theme_name]

            # Styled link with hover support
            self.folder_display.setText(
                f"""
                <style>
                    a {{
                        color: {current_theme['accent']};
                        text-decoration: none;
                    }}
                    a:hover {{
                        color: {current_theme['button_hover']};
                    }}
                </style>
                <a href="open">{folder}</a>
                """
            )

            # Keep your existing logic
            self.btn_start.setEnabled(True)
            self.log.append(f"Output folder set to: {folder}\n")
            self.status.showMessage("Output folder selected")

            self.config["output_folder"] = folder
            save_config(self.config)

    def open_output_folder(self, link):
        folder = self.output_dir
        if not folder:
            return

        # Cross‑platform folder opening
        if sys.platform.startswith("linux"):
            subprocess.Popen(["xdg-open", folder])
        elif sys.platform.startswith("win"):
            os.startfile(folder)
        elif sys.platform.startswith("darwin"):
            subprocess.Popen(["open", folder])

    def start_rip(self):
        # ===========================
        # Basic validation
        # ===========================
        if not self.output_dir:
            QMessageBox.warning(self, "Error", "Select an output folder first.")
            return

        title = self.title_input.text().strip()
        year = self.year_input.text().strip()
        genre = self.genre_input.text().strip()

        if not title or not year:
            QMessageBox.warning(self, "Error", "Title and Year are required.")
            return

        drive = self.drive_box.currentData()
        if not drive:
            QMessageBox.warning(self, "Error", "No drive selected.")
            return

        # Warn about MATSHITA RPC lock
        if "MATSHITA" in drive["model"]:
            QMessageBox.warning(
                self,
                "Warning",
                "Selected drive is MATSHITA and may fail due to RPC lock.\n"
                "Consider using another drive."
            )

        # ===========================
        # Reset STOP flags
        # ===========================
        self.stop_requested = False
        if self.worker:
            self.worker.stop_requested = False

        # ===========================
        # Save last-used drive
        # ===========================
        self.config["last_used_drive"] = drive["dev"]
        save_config(self.config)

        # ===========================
        # Prepare UI
        # ===========================
        self.btn_stop_all.setEnabled(True)
        self.btn_start.setEnabled(False)
        self.progress.setValue(0)
        self.status.showMessage("Starting rip…")

        # ===========================
        # Create worker (NEW SIGNATURE)
        # ===========================
        self.worker = RipWorker(
            gui=self,                # <-- REQUIRED for kill switch
            output_dir=self.output_dir,
            drive_info=drive,
            title=title,
            year=year,
            genre=genre
        )

        # ===========================
        # Connect worker signals
        # ===========================
        self.worker.log.connect(self.log.append)
        self.worker.done.connect(self.finish)
        self.worker.status.connect(self.status.showMessage)
        self.worker.progress.connect(self.progress.setValue)

        # ===========================
        # Start worker thread
        # ===========================
        self.worker.start()
    
    def update_output_folder_display(self):
        current_theme = self.config["themes"][self.theme_name]

        self.folder_display.setText(
            f"""
            <style>
                a {{
                    color: {current_theme['accent']};
                    text-decoration: none;
                }}
                a:hover {{
                    color: {current_theme['button_hover']};
                }}
            </style>
            <a href="open">{self.output_dir}</a>
            """
        )

    def kill_all_processes(self):
        self.stop_requested = True
        self.status.showMessage("Stopping all processes...")
        self.log.append(f"User requested to stop all processes.\n")

        # Kill all ffmpeg processes
        for proc in self.active_processes:
            try:
                proc.kill()
            except Exception:
                pass

        self.active_processes.clear()

        # Stop workers
        try:
            if hasattr(self, "worker") and self.worker is not None:
                self.worker.stop_requested = True
        except Exception:
            pass

        # Disable UI actions
        self.btn_start.setEnabled(False)
        self.btn_stop_all.setEnabled(False)

        self.status.showMessage("All processes stopped")
        self.log.append(f"All processes stopped by user.\n")

    def eject_disc(self):
        drive = self.drive_box.currentData()
        dev = drive["dev"]  # example: /dev/sr0

        self.status.showMessage(f"Ejecting {dev}…")
        self.log.append(f"Attempting to eject disc from {dev}\n")

        try:
            # Linux eject command
            subprocess.run(["eject", dev], check=True)
            self.status.showMessage("Disc ejected")
            self.log.append(f"Disc ejected from {dev}\n")
        except Exception as e:
            QMessageBox.warning(self, "Eject Failed", f"Could not eject disc:\n{e}")
            self.status.showMessage("Eject failed")
            self.log.append(f"Failed to eject disc from {dev}\n")

    def finish(self, result):
        # Worker is done — disable Stop All
        self.btn_stop_all.setEnabled(False)

        # Clear active worker reference
        self.worker = None

        # ===========================
        # STOPPED
        # ===========================
        if result == "STOPPED":
            self.log.append("\n=== STOPPED ===\nAll processes were terminated by user.\n")
            self.status.showMessage("Stopped")
            self.progress.setValue(0)
            self.btn_start.setEnabled(True)
            return

        # ===========================
        # ERROR
        # ===========================
        if isinstance(result, str) and result.startswith("ERROR:"):
            self.log.append(f"\n{result}\n")
            self.status.showMessage("Error during ripping")
            self.progress.setValue(0)
            self.btn_start.setEnabled(True)
            return

        # ===========================
        # SUCCESS
        # ===========================
        self.log.append(f"\n=== Completed ===\nOutput folder: {result}\n")
        self.status.showMessage("Rip completed successfully")
        self.progress.setValue(100)

        # Auto-eject only on success
        if self.auto_eject_enabled:
            try:
                self.eject_disc()
            except Exception as e:
                self.log.append(f"Warning: Auto-eject failed: {e}\n")

        # Re-enable Start button
        self.btn_start.setEnabled(True)
    
    def reset_fields(self):
        self.title_input.clear()
        self.year_input.clear()
        self.genre_input.clear()
        self.status.showMessage("Fields reset")

    def show_tmdb_help(self):
        QMessageBox.information(
            self,
            "TMDB API Key Instructions",
            "To enable TMDB metadata lookup:\n\n"
            "1. Visit https://www.themoviedb.org/settings/api\n"
            "2. Create a free account\n"
            "3. Request an API key\n"
            "4. Open File → Settings and paste your key\n\n"
            "TMDB features remain disabled until a valid key is saved."
        )

    def show_about(self):
        about = QDialog(self)
        about.setWindowTitle("About")
        about.setWindowIcon(QIcon.fromTheme("dvd-ripper"))  # use your app icon

        layout = QVBoxLayout(about)

        icon_label = QLabel()
        icon_label.setPixmap(QIcon.fromTheme("dvd-ripper").pixmap(64, 64))
        layout.addWidget(icon_label, alignment=Qt.AlignHCenter)

        text = QLabel(
            "MediaSuite DVD Ripper<br>"
            "Version 1.0.0<br><br>"
            "Created by Bill Swords<br>"
            "Includes MakeMKV, HandBrake, and TMDB metadata support."
        )
        text.setTextFormat(Qt.RichText)
        text.setAlignment(Qt.AlignCenter)
        layout.addWidget(text)

        ok_btn = QPushButton("OK")
        ok_btn.clicked.connect(about.accept)
        layout.addWidget(ok_btn, alignment=Qt.AlignCenter)

        about.exec()

    def open_settings(self):
        drives = detect_drives()
        dlg = SettingsDialog(self, self.tmdb_key, self.config, drives)
        if dlg.exec():
            new_key = dlg.get_key()
            save_tmdb_key(new_key)
            self.tmdb_key = new_key
            self.config["tmdb_api_key"] = new_key

            # New settings
            self.auto_eject_enabled = dlg.get_auto_eject()
            self.auto_tmdb_enabled = dlg.get_auto_tmdb_lookup()
            self.auto_select_disc_drive = dlg.get_auto_select_disc_drive()
            self.default_drive = dlg.get_default_drive()
            self.theme_name = dlg.get_theme()
            self.auto_scan_startup = dlg.get_auto_scan_startup()
            self.auto_scan_insert = dlg.get_auto_scan_insert()
            self.auto_scan_remove = dlg.get_auto_scan_remove()
            self.theme_name = dlg.get_theme()

            self.config["auto_eject"] = self.auto_eject_enabled
            self.config["auto_tmdb_lookup"] = self.auto_tmdb_enabled
            self.config["auto_select_disc_drive"] = self.auto_select_disc_drive
            self.config["default_drive"] = self.default_drive
            self.config["theme"] = self.theme_name
            self.config["auto_scan_startup"] = self.auto_scan_startup
            self.config["auto_scan_insert"] = self.auto_scan_insert
            self.config["auto_scan_remove"] = self.auto_scan_remove
            self.config["theme"] = self.theme_name
            save_config(self.config)
            self.apply_theme(self.theme_name)

            if new_key:
                self.tmdb_lookup_btn.setEnabled(True)
                self.status.showMessage("TMDB key saved")
            else:
                self.tmdb_lookup_btn.setEnabled(False)
                self.status.showMessage("TMDB key cleared")

            self.status.showMessage("Settings saved")

    def lookup_tmdb(self):
        if not self.tmdb_key:
            QMessageBox.warning(self, "Error", "TMDB key required.")
            return

        title = self.title_input.text().strip()
        year = self.year_input.text().strip()

        if not title:
            QMessageBox.warning(self, "Error", "Enter a title first.")
            return

        data = tmdb_lookup(title, year, self.tmdb_key)
        if not data:
            QMessageBox.warning(self, "Not Found", "No TMDB match found.")
            return

        self.title_input.setText(data.get("title", title))
        self.year_input.setText(str(data.get("release_date", "")[:4]))

        genre_ids = data.get("genre_ids", [])
        if genre_ids:
            genre_url = "https://api.themoviedb.org/3/genre/movie/list"
            r = requests.get(genre_url, params={"api_key": self.tmdb_key})
            if r.status_code == 200:
                genre_map = {g["id"]: g["name"] for g in r.json().get("genres", [])}
                genres = [genre_map.get(gid, "") for gid in genre_ids]
                self.genre_input.setText(", ".join(genres))

        QMessageBox.information(self, "TMDB Lookup", "Metadata imported successfully.")

    def auto_tmdb_lookup(self):
        # Prevent duplicate lookups
        if getattr(self, "tmdb_lookup_running", False):
            return
        self.tmdb_lookup_running = True

        try:
            title = self.title_input.text().strip()
            if not title:
                return

            data = tmdb_lookup(title, "", self.tmdb_key)
            if not data:
                QMessageBox.information(self, "TMDB Lookup", "No metadata found for this disc.")
                return

            # Auto-fill fields
            self.title_input.setText(data.get("title", title))
            self.year_input.setText(str(data.get("release_date", "")[:4]))

            genre_ids = data.get("genre_ids", [])
            if genre_ids:
                genre_url = "https://api.themoviedb.org/3/genre/movie/list"
                r = requests.get(genre_url, params={"api_key": self.tmdb_key})
                if r.status_code == 200:
                    genre_map = {g["id"]: g["name"] for g in r.json().get("genres", [])}
                    genres = [genre_map.get(gid, "") for gid in genre_ids]
                    self.genre_input.setText(", ".join(genres))

            QMessageBox.information(self, "TMDB Lookup", "Metadata imported successfully.")

        finally:
            # Always clear the flag so future lookups can run
            self.tmdb_lookup_running = False

    def apply_theme(self, theme_name):
        theme = self.config["themes"].get(theme_name)
        if not theme:
            return

        self.setStyleSheet(f"""
            QWidget {{
                background-color: {theme['background']};
                color: {theme['text']};
                border-radius: 6px;
            }}
            QLineEdit, QTextEdit, QComboBox {{
                background-color: {theme['input_bg']};
                color: {theme['text']};
                border: 1px solid {theme['border']};
                border-radius: 6px;
                padding: 3px;
            }}
            QPushButton {{
                background-color: {theme['button_bg']};
                color: {theme['text']};
                border: 1px solid {theme['border']};
                border-radius: 6px;
                padding: 4px;
            }}
            QPushButton:disabled {{
                background-color: #b0b0b0;   /* lighter grey for disabled state */
                color: #666666;              /* dimmed text */
                border: 1px solid #999999;
                border-radius: 6px;
            }}
            QPushButton:hover {{
                background-color: {theme['button_hover']};
            }}
            QProgressBar {{
                background-color: {theme['input_bg']};
                border: 1px solid {theme['border']};
                border-radius: 6px;
                text-align: center;
            }}
            QProgressBar::chunk {{
                background-color: {theme['accent']};
                border-radius: 6px;
            }}
            QComboBox::drop-down {{
                border: none;
                border-radius: 6px;
                width: 20px;
            }}
            QComboBox QAbstractItemView {{
                background-color: {theme['input_bg']};
                color: {theme['text']};
                border: 1px solid {theme['border']};
                border-radius: 6px;          /* rounds the dropdown itself */
                selection-background-color: {theme['accent']};
                selection-color: {theme['text']};
            }}
            QLabel {{
                color: {theme['text']};
            }}
            QLabel#outputPath {{
                color: {theme['accent']};
            }}
            QLabel#outputPath:hover {{
                color: {theme['button_hover']};
            }}
        """)

        # Re-style output folder link when theme changes
        if hasattr(self, "folder_display") and getattr(self, "output_dir", None):
            current_theme = self.config["themes"][self.theme_name]

            self.folder_display.setText(
                f"""
                <style>
                    a {{
                        color: {current_theme['accent']};
                        text-decoration: none;
                    }}
                    a:hover {{
                        color: {current_theme['button_hover']};
                    }}
                </style>
                <a href="open">{self.output_dir}</a>
                """
            )

    def find_top_level_strays(self):
        if not self.output_dir:
            return []

        strays = []
        for f in os.listdir(self.output_dir):
            full = os.path.join(self.output_dir, f)
            if f.endswith(".mkv") and os.path.isfile(full):
                strays.append(full)

        return strays

# ===========================
# Stray Cleanup Dialog
# ===========================
class StrayCleanupDialog(QDialog):
    def __init__(self, parent, stray_files):
        super().__init__(parent)
        self.setWindowTitle("Stray MKV Cleanup")
        self.setMinimumWidth(500)

        self.new_output_dir = None
        self.stray_files = stray_files

        layout = QVBoxLayout(self)

        msg = QLabel(
            "The following stray MKV files were found in your output folder.\n"
            "Select the ones you want to delete, or change the output directory instead."
        )
        msg.setWordWrap(True)
        layout.addWidget(msg)

        self.checkboxes = []
        for f in stray_files:
            cb = QCheckBox(f)
            cb.setChecked(True)
            self.checkboxes.append(cb)
            layout.addWidget(cb)

        # Buttons
        btn_layout = QHBoxLayout()

        delete_btn = QPushButton("Delete Selected")
        delete_btn.clicked.connect(self.accept)
        btn_layout.addWidget(delete_btn)

        change_btn = QPushButton("Change Output Directory")
        change_btn.clicked.connect(self.change_output_dir)
        btn_layout.addWidget(change_btn)

        cancel_btn = QPushButton("Cancel")
        cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(cancel_btn)

        layout.addLayout(btn_layout)

    def selected_files(self):
        return [cb.text() for cb in self.checkboxes if cb.isChecked()]

    def change_output_dir(self):
        new_dir = QFileDialog.getExistingDirectory(self, "Select New Output Folder")
        if new_dir:
            self.new_output_dir = new_dir
            self.accept()

#===========================
# Dependency Installer Dialog
#===========================
class DependencyInstallerDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Installing Dependencies")
        self.setModal(True)
        self.resize(400, 150)

        layout = QVBoxLayout(self)

        self.label = QLabel("Installing MakeMKV and HandBrake…")
        layout.addWidget(self.label)

        self.progress = QProgressBar()
        self.progress.setRange(0, 0)  # infinite spinner
        layout.addWidget(self.progress)

        self.process = QProcess(self)
        self.process.readyReadStandardOutput.connect(self.on_output)
        self.process.readyReadStandardError.connect(self.on_output)
        self.process.finished.connect(self.on_finished)

        # Start installer
        self.process.start("pkexec", ["/usr/share/dvd-ripper/install-deps.sh"])

    def on_output(self):
        data = self.process.readAllStandardOutput().data().decode()
        if data.strip():
            self.label.setText(data.strip())

    def on_finished(self):
        self.accept()

# ===========================
# Main
# ===========================

if __name__ == "__main__":
    app = QApplication(sys.argv)

    if not ensure_dependencies():
        print("Could not install dependencies.")
        sys.exit(1)

    icon_path = Path(__file__).parent / "icons" / "dvd-ripper.png"
    app.setWindowIcon(QIcon(str(icon_path)))

    gui = DVDGui()
    gui.show()
    sys.exit(app.exec())
