from urllib.parse import urlparse, parse_qs
from django import template
 
register = template.Library()
 
FLAG_MAP = {
    'en': '🇬🇧',
    'nl': '🇳🇱',
    'zh': '🇨🇳',
    'ja': '🇯🇵',
    'fr': '🇫🇷',
    'es': '🇪🇸',
    'it': '🇮🇹',
    'de': '🇩🇪',
    'pt': '🇵🇹',
    'ru': '🇷🇺',
    'hi': '🇮🇳',
}
 
@register.filter
def language_flag(lang_code):
    return FLAG_MAP.get(lang_code, '🌐')

@register.filter
def video_embed_url(video_url):
    """
    Converts YouTube/Vimeo URLs into iframe-friendly embed URLs.
    Supports:
    - youtube.com/watch?v=
    - youtu.be/
    - youtube.com/embed/
    - youtube.com/shorts/
    - vimeo.com/
    """
    if not video_url:
        return ''

    try:
        parsed = urlparse(video_url)
        domain = parsed.netloc.lower().replace('www.', '')
        path = parsed.path.strip('/')

        # YouTube normal watch URL:
        # https://www.youtube.com/watch?v=VIDEO_ID
        if domain in ['youtube.com', 'm.youtube.com']:
            query = parse_qs(parsed.query)

            if path == 'watch':
                video_id = query.get('v', [''])[0]
                if video_id:
                    return f'https://www.youtube.com/embed/{video_id}'

            # Already embed URL:
            # https://www.youtube.com/embed/VIDEO_ID
            if path.startswith('embed/'):
                video_id = path.split('embed/')[-1].split('/')[0]
                if video_id:
                    return f'https://www.youtube.com/embed/{video_id}'

            # YouTube Shorts:
            # https://www.youtube.com/shorts/VIDEO_ID
            if path.startswith('shorts/'):
                video_id = path.split('shorts/')[-1].split('/')[0]
                if video_id:
                    return f'https://www.youtube.com/embed/{video_id}'

        # Short YouTube URL:
        # https://youtu.be/VIDEO_ID
        if domain == 'youtu.be':
            video_id = path.split('/')[0]
            if video_id:
                return f'https://www.youtube.com/embed/{video_id}'

        # Vimeo:
        # https://vimeo.com/VIDEO_ID
        if domain == 'vimeo.com':
            video_id = path.split('/')[0]
            if video_id:
                return f'https://player.vimeo.com/video/{video_id}'

        # Already iframe-friendly or other embeddable URL
        return video_url

    except Exception:
        return video_url