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 extract_video_id(url: str):
    try:
        if "watch?v=" in url:
            return url.split("watch?v=")[1].split("&")[0]
        elif "youtu.be/" in url:
            return url.split("youtu.be/")[1].split("?")[0]
    except Exception:
        pass
    return None


def yt_thumbnail(url: str):
    vid = extract_video_id(url)
    if not vid:
        return None
    return f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg"


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

            vid = extract_video_id(item["url"])

            songs.append({
                "title": item.get("title", "Unknown"),
                "url": item["url"],
                "duration": sec_to_mmss(item.get("duration", "0")),
                "views": item.get("views", "Unknown"),
                "video_id": vid,
                "thumb": yt_thumbnail(item["url"]),
                "stream": stream,
            })

        return songs or None

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

        vid = extract_video_id(query)

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

    # 🔍 SEARCH QUERY
    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

    vid = extract_video_id(i["url"])

    return [{
        "title": i["title"],
        "url": i["url"],
        "duration": i.get("duration", "Unknown"),
        "views": i.get("views", "Unknown"),
        "video_id": vid,
        "thumb": i.get("thumbnail") or yt_thumbnail(i["url"]),
        "stream": stream,
    }]
