import hashlib
from typing import Iterable, List

from maps_adv.export.lib.core.enum import ActionType, CreativeType


def _generate_search_tag(campaign_id: int, companies: Iterable[int]) -> dict:
    companies = sorted(set(companies))

    search_tag_hash = hashlib.sha256()
    for company_id in companies:
        search_tag_hash.update(str(company_id).encode())
    search_tag_hash = search_tag_hash.hexdigest()[:32]

    return dict(id=f"search_tag-{campaign_id}-{search_tag_hash}", companies=companies)


def _generate_search_tag_for_campaign_category(campaign: dict) -> List[dict]:
    search_tags = []
    creatives = campaign["creatives"]

    if CreativeType.ICON in creatives:
        icon = creatives[CreativeType.ICON]

        search_tag = _generate_search_tag(campaign["id"], icon["organizations"].keys())

        icon["search_tag_id"] = search_tag["id"]
        search_tags.append(search_tag)

    return search_tags


def _generate_search_tag_for_actions(campaign: dict) -> List[dict]:
    search_tags = []

    for action in campaign["actions"]:
        if action["type"] == ActionType.SEARCH:
            action_search_tag = _generate_search_tag(
                campaign["id"], action["organizations"].keys()
            )
            action["search_tag_id"] = action_search_tag["id"]
            search_tags.append(action_search_tag)

    return search_tags


async def search_tags_resolver(campaigns: list) -> list:
    search_tags = list()

    for campaign in campaigns:
        search_tags.extend(_generate_search_tag_for_actions(campaign))
        search_tags.extend(_generate_search_tag_for_campaign_category(campaign))

    # deduplicate search tags
    search_tags_ids = set()
    deduplicated_search_tags = []
    for search_tag in search_tags:
        search_tag_id = search_tag["id"]
        if search_tag_id not in search_tags_ids:
            search_tags_ids.add(search_tag_id)
            deduplicated_search_tags.append(search_tag)

    return deduplicated_search_tags
