"""
Turn an external media URL into a player embed URL.

Used by the public watch page, the embeddable player, and anywhere else that
has to render a YouTube or SoundCloud item rather than our own HLS stream.
"""
import re
from urllib.parse import quote

# Covers watch, short links, embeds, Shorts and live streams, on the main
# domain or the mobile and music subdomains.
YOUTUBE_ID = re.compile(
    r'(?:'
    r'(?:www\.|m\.|music\.)?youtube\.com/watch\?(?:.*&)?v='
    r'|youtu\.be/'
    r'|(?:www\.|m\.)?youtube\.com/embed/'
    r'|(?:www\.|m\.)?youtube\.com/shorts/'
    r'|(?:www\.|m\.)?youtube\.com/live/'
    r'|(?:www\.|m\.)?youtube\.com/v/'
    r')'
    r'([A-Za-z0-9_-]{11})'
)


def embed_url(url, autoplay=False):
    """
    Return a URL suitable for an iframe src, or None if the link is not one
    we know how to embed.
    """
    if not url:
        return None

    match = YOUTUBE_ID.search(url)
    if match:
        params = 'rel=0&modestbranding=1'
        if autoplay:
            params += '&autoplay=1'
        return f'https://www.youtube.com/embed/{match.group(1)}?{params}'

    if 'soundcloud.com' in url:
        params = (
            'color=%23033152&hide_related=true'
            '&show_comments=false&show_user=false&show_reposts=false'
        )
        if autoplay:
            params += '&auto_play=true'
        return f'https://w.soundcloud.com/player/?url={quote(url, safe="")}&{params}'

    return None


def is_external(item):
    """True if this item streams from someone else's platform."""
    return bool(getattr(item, 'source_url', ''))
