import re
from YouTubeMusic.Search import Search
from YouTubeMusic.Stream import get_stream
from YouTubeMusic.Playlist import get_playlist_songs

PLAYLIST_REGEX = re.compile(r"(list=)")
YOUTUBE_REGEX = re.compile(r"(youtube\.com|youtu\.be|music\.youtube\.com)")

def sec_to_mmss(sec):
    try:
        sec = int(sec)
        return f"{sec // 60}:{sec % 60:02d}"
    except Exception:
        return "Unknown"

def yt_thumbnail(url: str):
    """Extract thumbnail from YouTube URL"""
    try:
        if "watch?v=" in url:
            vid = url.split("watch?v=")[1].split("&")[0]
        elif "youtu.be/" in url:
            vid = url.split("youtu.be/")[1].split("?")[0]
        else:
            return None
        return f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg"
    except Exception:
        return None


async def resolve_query(query: str):
    songs = []

    # 🎵 PLAYLIST
    if PLAYLIST_REGEX.search(query):
        playlist = await get_playlist_songs(query)
        for item in playlist:
            stream = get_stream(item["url"])
            if not stream:
                continue

            songs.append({
                "title": item.get("title", "Unknown"),
                "url": item["url"],
                "duration": sec_to_mmss(item.get("duration", "0")),
                "views": "Unknown",
                "thumbnail": yt_thumbnail(item["url"]),
                "stream": stream,
            })
        return songs or None

    # 🔗 DIRECT YT LINK
    if YOUTUBE_REGEX.search(query):
        stream = get_stream(query)
        if not stream:
            return None

        return [{
            "title": "YouTube Audio",
            "url": query,
            "duration": "Unknown",
            "views": "Unknown",
            "thumbnail": yt_thumbnail(query),
            "stream": stream,
        }]

    # 🔍 SEARCH
    res = await Search(query, limit=1)
    if not res or not res.get("main_results"):
        return None

    i = res["main_results"][0]
    stream = get_stream(i["url"])
    if not stream:
        return None

    return [{
        "title": i["title"],
        "url": i["url"],
        "duration": i.get("duration", "Unknown"),
        "views": i.get("views", "Unknown"),
        # 🔥 thumbnail from search (fallback safe)
        "thumbnail": i.get("thumbnail") or yt_thumbnail(i["url"]),
        "stream": stream,
    }]
