import os
import subprocess
from pathlib import Path

# Set paths relative to where this script file lives
SCRIPT_DIR = Path(__file__).parent.resolve()
YT_DLP_BIN = SCRIPT_DIR / "yt-dlp"
PLAYLIST_FILE = SCRIPT_DIR / "playlist_urls.txt"
DOWNLOAD_DIR = SCRIPT_DIR / "downloads"
ARCHIVE_FILE = SCRIPT_DIR / "downloaded_archive.txt"

def main():
    if not YT_DLP_BIN.exists():
        print(f"Error: Could not find 'yt-dlp' executable at {YT_DLP_BIN}")
        return

    if not PLAYLIST_FILE.exists():
        print(f"Error: Could not find '{PLAYLIST_FILE.name}' at {PLAYLIST_FILE}")
        return

    # Ensure executable permission is set on Ubuntu
    if not os.access(YT_DLP_BIN, os.X_OK):
        print(f"Adding execute permissions to {YT_DLP_BIN.name}...")
        os.chmod(YT_DLP_BIN, 0o755)

    # Build yt-dlp command line arguments
    cmd = [
        str(YT_DLP_BIN),
        "-x",                                     # Extract audio
        "--audio-format", "mp3",                  # Convert to MP3
        "--audio-quality", "192K",                # Preferred audio quality
        "-o", f"{DOWNLOAD_DIR}/%(playlist_title)s/%(title)s.%(ext)s",
        "--download-archive", str(ARCHIVE_FILE),  # Prevents re-downloading existing tracks
        "--ignore-errors",                        # Skips deleted/private videos automatically
        "-a", str(PLAYLIST_FILE)                  # Batches directly from the URL file
    ]

    print("Starting download process...\n")
    try:
        subprocess.run(cmd, check=True)
        print("\nDownload process completed successfully!")
    except subprocess.CalledProcessError as e:
        print(f"\nyt-dlp finished with errors (exit code {e.returncode}). Check output above.")

if __name__ == "__main__":
    main()