#!/usr/bin/env python3
"""
This script receives a YouTube URL on stdin, and removes the `list`
query parameter.

I use this in conjunction with `furl` and `youtube-dl`.  Sometimes
I want to download a single video from YouTube, but youtube-dl tries
to download an entire playlist.  This lets me grab just the first video.
"""

import sys
import urllib.parse

import pytest


def noplaylist(url: str) -> str:
    """
    Remove the playlist query parameters from a URL.
    """
    u = urllib.parse.urlsplit(url)

    query = urllib.parse.parse_qs(u.query)
    for name in ("list", "index", "pp"):
        try:
            del query[name]
        except KeyError:
            pass

    return urllib.parse.urlunsplit(
        (
            u.scheme,
            u.netloc,
            u.path,
            urllib.parse.urlencode(query, doseq=True),
            u.fragment,
        )
    )


@pytest.mark.parametrize(
    "original_url, url",
    [
        (
            "https://www.youtube.com/watch?v=wrhDXOZoQ74&list=PL7lRfPsqWBLZ9HK6t-BBaVBgRlkLg_FNI&index=4&pp=iAQB",
            "https://www.youtube.com/watch?v=wrhDXOZoQ74",
        ),
        (
            "https://www.youtube.com/watch?v=wrhDXOZoQ74",
            "https://www.youtube.com/watch?v=wrhDXOZoQ74",
        ),
    ],
)
def test_noplaylist(original_url: str, url: str) -> None:
    """
    Tests for `noplaylist()`.
    """
    assert noplaylist(original_url) == url


if __name__ == "__main__":
    url = sys.stdin.read()
    url = noplaylist(url)
    sys.stdout.write(url)
