import subprocess
from pathlib import Path
from config import settings

def is_playlist(query: str) -> bool:
    return "playlist" in query or "list=" in query

def download_song(query: str):
    Path(settings.MUSIC_DIR).mkdir(parents=True, exist_ok=True)
    output_template = f"{settings.MUSIC_DIR}/%(title)s.%(ext)s"
    command = [
        "yt-dlp",
        f"{query if query.startswith('http') else f'ytsearch1:{query}'}",
        "--extract-audio",
        "--audio-format", "mp3",
        "--add-metadata",
        "--output", output_template,
        "--verbose"
    ]
    # Only add --no-playlist for search queries
    if not is_playlist(query) and not query.startswith("http"):
        command.append("--no-playlist")

    print("Running command:", " ".join(command))
    result = subprocess.run(command, capture_output=True, text=True)
    print("STDOUT:", result.stdout)
    print("STDERR:", result.stderr)
    if result.returncode != 0:
        raise Exception(f"yt-dlp failed: {result.stderr}")
    return {"downloaded": "Check music folder for downloaded files"}