import asyncio from apollo_utils.core.constants.market import Market from apollo_utils.core.utils.ext_enum import ALL from server.client import services from server.constants import DSP from server.domains.markets.ranks import get_markets_ranks, set_missing_ranks from server.domains.tracks.common import calc_change_percent from server.domains.tracks.insights import get_two_weeks_and_last_day_streams from server.utils.common import get_last_date_by_weekday async def get_tracks_insights( isrc: str, dsp: str, include_worldwide: bool = False, include_zero_weeks: bool = False ) -> list[dict]: """Get tracks top country codes by streams. Args: isrc: Track ISRC code. dsp: DSP code or all. include_worldwide: Include worldwide or not. include_zero_weeks: Include 0 strike weeks or remove them. Returns: List of track's top country codes with additional data. """ dsp = None if dsp == ALL else DSP(dsp) result, country_code_rank_map = await asyncio.gather( *[ services.dsp.get_streams_insights(isrc=isrc, **({"dsp": dsp.value} if dsp else {})), get_markets_ranks(dsp=(dsp if dsp else DSP.SPOTIFY)), ] ) result = result[dsp.value] if dsp else result["all_dsps"] country_code_list = set() for index in range(len(result) - 1, -1, -1): item = result[index] country_code = item["country_code"] if (not include_worldwide and country_code == Market.WORLDWIDE) or ( not include_zero_weeks and not item["strike_weeks"] ): del result[index] else: country_code_list.add(country_code) country_code_list = list(country_code_list) if not country_code_list: return result country_code_rank_map = set_missing_ranks(country_code_rank_map, country_code_list) latest_date = get_last_date_by_weekday(3) streams_map = await get_two_weeks_and_last_day_streams(isrc, dsp, country_code_list, latest_date) for item in result: country_code = item["country_code"] item.update(streams_map[dsp.value if dsp else dsp][country_code]) item["rank"] = country_code_rank_map[country_code] item["trend"] = calc_change_percent(item["streams_last_week"], item["streams_previous_week"]) return result