"""
Custom template tags and filters for the business app.
"""
from django import template
import re

register = template.Library()


@register.filter(name='replace')
def replace(value, args):
    """
    Replace occurrences of a string with another string.
    Usage: {{ value|replace:"old,new" }}
    """
    if not value:
        return value

    try:
        old, new = args.split(',')
        return value.replace(old, new)
    except ValueError:
        return value


@register.filter(name='youtube_embed')
def youtube_embed(url):
    """
    Convert a YouTube URL to an embed URL.
    Handles various YouTube URL formats:
    - https://www.youtube.com/watch?v=VIDEO_ID
    - https://youtu.be/VIDEO_ID
    - https://www.youtube.com/embed/VIDEO_ID
    """
    if not url:
        return url

    # Already an embed URL
    if 'embed/' in url:
        return url

    # Extract video ID from different URL formats
    video_id = None

    # Format: youtube.com/watch?v=VIDEO_ID
    match = re.search(r'youtube\.com/watch\?v=([^&]+)', url)
    if match:
        video_id = match.group(1)

    # Format: youtu.be/VIDEO_ID
    if not video_id:
        match = re.search(r'youtu\.be/([^?]+)', url)
        if match:
            video_id = match.group(1)

    if video_id:
        return f'https://www.youtube.com/embed/{video_id}'

    return url


@register.filter(name='phone_whatsapp')
def phone_whatsapp(phone):
    """
    Convert phone number to WhatsApp format (remove + and spaces).
    """
    if not phone:
        return ''

    # Remove +, spaces, dashes, and parentheses
    return re.sub(r'[\s\-\(\)\+]', '', str(phone))
