import subprocess
import os
import glob
import requests
from config import settings

def download_song(query: str):
    # ודא שהתיקייה קיימת
    os.makedirs(settings.MUSIC_DIR, exist_ok=True)

    output_template = os.path.join(settings.MUSIC_DIR, "%(title)s.%(ext)s")
    before_files = set(glob.glob(os.path.join(settings.MUSIC_DIR, "**/*.mp3"), recursive=True))

    command = [
        "yt-dlp",
        f"ytsearch1:{query}",
        "--extract-audio",
        "--audio-format", "mp3",
        "-o", output_template,
        "--no-playlist"
    ]

    print("Running command:", " ".join(command))  # Debug

    result = subprocess.run(command, capture_output=True, text=True)

    after_files = set(glob.glob(os.path.join(settings.MUSIC_DIR, "**/*.mp3"), recursive=True))
    new_files = list(after_files - before_files)

    if result.returncode != 0:
        raise Exception(f"❌ Download failed:\n{result.stderr}")

    rescan_status = "skipped"
    if settings.NAVIDROME_SCAN_URL:
        try:
            res = requests.get(settings.NAVIDROME_SCAN_URL, timeout=5)
            res.raise_for_status()
            rescan_status = "triggered"
        except Exception as e:
            rescan_status = f"failed: {e}"

    return {
        "status": "success",
        "query": query,
        "downloaded_files": new_files,
        "yt_dlp_stdout": result.stdout,
        "yt_dlp_stderr": result.stderr,
        "rescan_status": rescan_status
    }
