import re
from typing import Optional

JIOSAAVN_URL_PATTERNS = {
    "track": re.compile(r"jiosaavn\.com/song/[^/]+/([^/]+)$"),
    "album": re.compile(r"jiosaavn\.com/album/[^/]+/([^/]+)$"),
    "artist": re.compile(r"jiosaavn\.com/artist/[^/]+/([^/]+)$"),
    "playlist": re.compile(
        r"(?:jiosaavn\.com|saavn\.com)/(?:featured|s/playlist)/[^/]+/[^/]+/([^/]+)$|(?:/([^/]+)$)"
    ),
}

JIOSAAVN_URL_PATTERN = re.compile(
    r"https?://(?:www\.)?(?:jiosaavn|saavn)\.com/"
)


def extract_id(url: str, content_type: str) -> Optional[str]:
    if not url or content_type not in JIOSAAVN_URL_PATTERNS:
        return None
    match = JIOSAAVN_URL_PATTERNS[content_type].search(url)
    if match:
        return match.group(1) or (match.group(2) if match.lastindex and match.lastindex >= 2 else None)
    return None


def extract_type(url: str) -> Optional[str]:
    if not url:
        return None
    if "/song/" in url:
        return "track"
    if "/album/" in url:
        return "album"
    if "/artist/" in url:
        return "artist"
    if "/featured/" in url or "/playlist/" in url:
        return "playlist"
    return None


def is_jiosaavn_url(text: str) -> bool:
    return bool(JIOSAAVN_URL_PATTERN.search(text))
