def build_competitive_landscape(client, brand_id: str, period: int = 30) -> dict:
data = client.get_competitors(
brand_id, period=period, limit=100,
sort='shareOfVoice', order='desc',
)
self_brand = next(
(item for item in data['competitors']
if item['relationship'] == 'SELF'),
None,
)
if self_brand is None:
raise ValueError('SELF brand is absent from the selected scope')
competitors = [
{
'id': item['id'],
'name': item['name'],
'mentions': item['totalMentions'],
'share_of_voice': item['shareOfVoice'],
'share_of_voice_gap': round(
item['shareOfVoice'] - self_brand['shareOfVoice'], 2
),
'average_position': item['avgPosition'],
'sentiment': item['avgSentiment'],
}
for item in data['competitors']
if item['relationship'] == 'DIRECT'
]
return {
'period': period,
'self': {
'id': self_brand['id'],
'name': self_brand['name'],
'mentions': self_brand['totalMentions'],
'share_of_voice': self_brand['shareOfVoice'],
},
'competitors': competitors,
}