import os
import shutil
import subprocess
import tarfile
import zipfile

def rclone_lsf_recursive(remote_path):
    """
    Holt extrem schnell ALLE Dateipfade rekursiv.
    Nur Namen, keine Metadaten. Das ist der Performance-King. 👑
    """
    # --files-only: Wir wollen keine leeren Ordnernamen, sondern die Dateien darin.
    cmd = ["rclone", "lsf", remote_path, "-R", "--files-only"]
    try:
        out = subprocess.check_output(cmd, text=True)
        return out.splitlines()
    except subprocess.CalledProcessError:
        return []

def rclone_copy(src, dest):
    """Lädt Dateien/Ordner herunter."""
    subprocess.run(["rclone", "copy", src, dest, "--progress"], check=True)

def rclone_delete(path, is_folder=False):
    """Löscht Remote (Purge für Ordner, deletefile für Datei)."""
    if is_folder:
        subprocess.run(["rclone", "purge", path], check=True)
    else:
        subprocess.run(["rclone", "deletefile", path], check=True)

def extract_archive(source_path, dest_dir):
    """Entpackt ZIP/TAR in Zielordner."""
    if os.path.exists(dest_dir): shutil.rmtree(dest_dir)
    os.makedirs(dest_dir, exist_ok=True)
    
    ext = str(source_path).lower()
    try:
        if ext.endswith(".zip"):
            with zipfile.ZipFile(source_path, 'r') as zip_ref:
                zip_ref.extractall(dest_dir)
            return True
        elif ext.endswith((".tar", ".tar.gz", ".tgz")):
            with tarfile.open(source_path, "r:*") as tar_ref:
                tar_ref.extractall(dest_dir)
            return True
    except Exception as e:
        print(f"❌ Fehler beim Entpacken: {e}")
    return False

def mount_dmg(dmg_path):
    """Mountet DMG und gibt Mountpoint zurück."""
    try:
        res = subprocess.check_output(["hdiutil", "attach", dmg_path, "-nobrowse"], text=True)
        for line in res.splitlines():
            if "/Volumes/" in line:
                return line.split("\t")[-1].strip()
    except Exception as e:
        print(f"❌ DMG Mount Fehler: {e}")
    return None

def unmount_dmg(mount_point):
    """Unmountet Pfad."""
    if mount_point:
        subprocess.run(["hdiutil", "detach", mount_point, "-quiet"], check=False)