import re

MUTAGEN_AVAILABLE = True
try:
    from mutagen.mp4 import MP4
except ImportError:
    MUTAGEN_AVAILABLE = False


def clean_channel_name(channel_name: str) -> str:
    """
    Clean channel name for ID3 tagging by removing @ symbol and ensuring it's alpha-only.
    
    Args:
        channel_name: Raw channel name (may contain @ symbol)
        
    Returns:
        Cleaned channel name suitable for ID3 tags
    """
    # Remove @ symbol if present
    if channel_name.startswith('@'):
        channel_name = channel_name[1:]
    
    # Remove any non-alphanumeric characters and convert to single word
    # Keep only letters, numbers, and spaces, then take the first word
    cleaned = re.sub(r'[^a-zA-Z0-9\s]', '', channel_name)
    words = cleaned.split()
    if words:
        return words[0]  # Return only the first word
    
    return "Unknown"


# Import the enhanced extract_artist_title function from fuzzy_matcher.py
# This ensures consistent parsing across all modules and supports multiple video title formats
from karaoke_downloader.fuzzy_matcher import extract_artist_title


def add_id3_tags(file_path, video_title, channel_name):
    if not MUTAGEN_AVAILABLE:
        print("⚠️ mutagen not available - skipping ID3 tagging")
        return
    try:
        artist, title = extract_artist_title(video_title)
        clean_channel = clean_channel_name(channel_name)
        mp4 = MP4(str(file_path))
        mp4["\xa9nam"] = title
        mp4["\xa9ART"] = artist
        mp4["\xa9alb"] = clean_channel  # Use clean channel name only, no suffix
        mp4["\xa9gen"] = "Karaoke"
        mp4.save()
        print(f"📝 Added ID3 tags: Artist='{artist}', Title='{title}', Album='{clean_channel}'")
    except Exception as e:
        print(f"⚠️ Could not add ID3 tags: {e}")
