"""Logic layer for the work with Spotify data.""" from owsresponse import response from participant.models.service import spotify as spotify_model def artist_search(query, limit, offset, localization): """Search artists by passed query. Args: query (str): Search term. limit (int): Max number of matched artists. offset (int): Offset from the beginning of the result. localization (str): Localization for the search. Returns: List: List of matched artists. """ result = spotify_model.search_artist(query, limit, offset, localization) return response.Response(_format_search_response(result)) def get_artist_by_id(artist_id): """Search artist by id. Args: artist_id (str): Artist ID to search. Returns: dict: Matched artist. """ result = spotify_model.get_artist_by_id(artist_id) if not result: return result return response.Response(_format_artist_response(result)) def get_artists_by_ids(artist_ids: list[str]): """Retrieve artists by ids. Args: artist_ids (list[str]): List of Spotify artist ids. Returns: dict[str, bool]: Mapping of artist id to artist object or None. """ result = spotify_model.get_artists_by_ids(artist_ids=artist_ids) if not result or not result.message: return result return response.Response( [ _format_artist_response(artist) for artist in result.message.values() if artist is not None ] ) def _format_search_response(artists): """Format Spotify response.""" if not isinstance(artists, dict) or 'artists' not in artists: return [] return [ { 'identifier': r['id'], 'name': r['name'], 'followers': r['followers']['total'], 'genres': r['genres'], 'url': r['external_urls']['spotify'], 'image': r['images'][-1]['url'] if r['images'] else None, } for r in artists['artists']['items'] ] def _format_artist_response(artist): """Format Spotify artist response.""" return { 'identifier': artist['id'], 'name': artist['name'], 'followers': artist['followers']['total'], 'genres': artist['genres'], 'url': artist['external_urls']['spotify'], 'image': artist['images'][-1]['url'] if artist['images'] else None, }