"""Logic for retrieving top markets information.""" from typing import Any, Mapping import oto.response from ddtrace import tracer from analytics.constants import cache from analytics.constants.store import ALL_TOP_MARKETS_SOURCES from analytics.logic.stores import add_outage_error_to_stores from analytics.queries.sound_recording_top_markets import TopMarkets from analytics.schemas.top_markets import TopMarketsSchema from analytics.utils import store_availability from analytics.utils.cache import cache_in_redis from analytics.validation.schema import schema_dump @cache_in_redis(ttl=cache.ONE_DAY) @tracer.wrap(name="get_top_markets") def get_top_markets( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ): """Return top markets for a sound recording. Args: query_params: Dict with isrc, distributors, country_ids, store_ids. permissions: Dict with permission_* keys. Returns: oto.response.Response with top markets payload. """ isrc = query_params["isrc"] response_body = { "isrc": isrc, "items": [], "sources": add_outage_error_to_stores(ALL_TOP_MARKETS_SOURCES), } schema = TopMarketsSchema() store_ids = query_params.get("store_ids", []) if not store_ids: store_ids = store_availability.get_store_ids() else: store_ids = sorted( list(set(store_ids).intersection(store_availability.get_store_ids())) ) if not store_ids: return oto.response.Response(schema_dump(schema, response_body)) query_input = { **permissions, "isrc": isrc, "store_ids": store_ids, "distributors": query_params["distributors"], "country_ids": query_params.get("country_ids", []), "transfer_product_ownership_enabled": query_params.get( "transfer_product_ownership_enabled", False ), } result = TopMarkets(query_input).execute() top_markets = [ dict(row._mapping) if hasattr(row, "_mapping") else dict(row) for row in result ] if top_markets: response_body["items"] = top_markets return oto.response.Response(schema_dump(schema, response_body))