import logging

import requests

logger = logging.getLogger(__name__)

LB_LABS_API = "https://labs.api.listenbrainz.org"
STANDARD_ALGORITHM = "session_based_days_180_session_300_contribution_5_threshold_15_limit_50_skip_30"
MLHD_ALGORITHM = "session_based_mlhd_session_300_contribution_5_threshold_15_limit_50_skip_30"
SIMILAR_ARTISTS_ALGORITHM = "session_based_days_1825_session_300_contribution_3_threshold_10_limit_100_filter_True_skip_30"


def get_similar_recordings(recording_mbid: str) -> list[dict]:
    """Fetch similar recordings from ListenBrainz.

    Tries the standard dataset first, falls back to MLHD dataset.
    Returns [] on error or no data.
    """
    if not recording_mbid:
        return []

    try:
        resp = requests.post(
            f"{LB_LABS_API}/similar-recordings/json",
            json=[
                {
                    "recording_mbids": [recording_mbid],
                    "algorithm": STANDARD_ALGORITHM,
                }
            ],
            timeout=10,
        )
        resp.raise_for_status()
        data = resp.json()
        if data:
            return data

        resp = requests.post(
            f"{LB_LABS_API}/mlhd-similar-recordings/json",
            json=[
                {
                    "recording_mbids": [recording_mbid],
                    "algorithm": MLHD_ALGORITHM,
                }
            ],
            timeout=10,
        )
        resp.raise_for_status()
        return resp.json()
    except requests.RequestException as e:
        logger.warning(
            "ListenBrainz similar recordings error",
            extra={
                "recording_mbid": recording_mbid,
                "error": str(e),
            },
        )
        return []


def get_similar_artists(artist_mbid: str) -> list[dict]:
    """Fetch similar artists from ListenBrainz.

    Returns [] on error or no data.
    """
    if not artist_mbid:
        return []

    try:
        resp = requests.post(
            f"{LB_LABS_API}/similar-artists/json",
            json=[
                {
                    "artist_mbids": [artist_mbid],
                    "algorithm": SIMILAR_ARTISTS_ALGORITHM,
                }
            ],
            timeout=10,
        )
        resp.raise_for_status()
        return resp.json()
    except requests.RequestException as e:
        logger.warning(
            "ListenBrainz similar artists error",
            extra={
                "artist_mbid": artist_mbid,
                "error": str(e),
            },
        )
        return []
