#!/usr/bin/env python3
"""
A simple script to pipe URIs through yt-dlp and mpd

Credit: https://gist.github.com/phaer/86bdcc3fb59cd3fcd9534bfe84d9fe5f
"""
import sys
import mpd
import yt_dlp

mpd_host = ('localhost', 6600)
ydl_opts = {
    'format': 'bestaudio/audio',
    'quiet': True,
}

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("usage: {} <url>".format(sys.argv[0]), file=sys.stderr)
        sys.exit(1)

    source_url = sys.argv[1]
    client = mpd.MPDClient()

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        try:
            info = ydl.extract_info(source_url, process=False, download=False)
        except yt_dlp.utils.DownloadError:
            # Don't print anything, yt-dlp is already on it
            sys.exit(1)

        if info.get("_type") is not None and info.get("_type") == "playlist":
            print("Queuing playlists not supported yet.", file=sys.stderr)
            sys.exit(1)

        info = ydl.process_ie_result(info, download=False)
        url = info.get('url')
        title = info.get('title')
        source = info.get('extractor_key')

        # This info is only available for songs
        # that have been tagged as such on youtube
        artist = info.get('artist')

    if not (url and title and source):
        print("youtube-dl error.", file=sys.stderr)
        sys.exit(1)

    client.connect(*mpd_host)

    # Get current playing song index and then append the stream just after
    # This is analogous to `mpc insert <song>`
    pos = int(client.status()["song"])
    song_id = client.addid(url, pos + 1)

    client.addtagid(song_id, 'title', title)
    client.addtagid(song_id, 'album', source)
    if artist is not None:
        client.addtagid(song_id, 'artist', artist)

    client.disconnect()