import json
from collections import OrderedDict
from itertools import chain

from maps_adv.adv_store.api.schemas.enums import PublicationEnvEnum
from maps_adv.export.lib.core.enum import CampaignType, CreativeType


def _get_search_text_from_icon(icon: dict) -> str:
    search_text = icon.get("search_text")
    if search_text is None:
        search_text = json.dumps(
            OrderedDict(
                [("text", ""), ("ad", dict(advert_tag_id=icon["search_tag_id"]))]
            )
        )
    return search_text


async def menu_item_transform(campaign: dict) -> dict:
    if campaign["campaign_type"] == CampaignType.CATEGORY:
        icon = campaign["creatives"][CreativeType.ICON]
        companies = set(
            chain(
                campaign["placing"]["organizations"].keys(),
                icon["organizations"].keys(),
            )
        )

        return dict(
            id="ac_auto_log_id_campaign_{}{}".format(
                campaign["id"],
                "_data_testing"
                if [PublicationEnvEnum.DATA_TESTING] == campaign["publication_envs"]
                else "",
            ),
            pages=campaign["pages"],
            companies=sorted(companies),
            style=icon["style"],
            title=[dict(value=icon["title"])],
            position=icon["position"],
            search_text=_get_search_text_from_icon(icon),
        )

    return dict()
