import hashlib
from typing import Iterable

from maps_adv.export.lib.config import config
from maps_adv.export.lib.core.enum import CampaignType, CreativeType, ImageType

ICON_STYLE_TEMPLATE = "{namespace}--{group_id}--{image_name}"
PIN_SEARCH_STYLE_TEMPLATE = "style_advert-{campaign_id}-{pin_search_hash}"
PIN_SEARCH_IMAGES_FOR_HASH = (
    ImageType.LOGO,
    ImageType.BANNER,
    ImageType.PIN_ROUND,
    ImageType.PIN_SELECTED,
)


def _images_to_dict(images: Iterable[dict]) -> dict:
    return {image["type"]: image for image in images}


def _calculate_hash_for_images(images: dict, order_images: Iterable[ImageType]) -> str:
    images_hash = hashlib.sha256()
    for image_type in order_images:
        if image_type in images:
            image = images[image_type]
            images_hash.update(
                "{image_name}:{group_id}".format(
                    image_name=image["image_name"], group_id=image["group_id"]
                ).encode()
            )
    return images_hash.hexdigest()


def _resolve_campaign_category(campaign: dict):
    creatives = campaign["creatives"]

    icon = creatives[CreativeType.ICON]
    icon_images = _images_to_dict(icon["images"])

    image_category = icon_images[ImageType.CATEGORY]
    icon["style"] = ICON_STYLE_TEMPLATE.format(
        namespace=config.AVATARS_NAMESPACE,
        group_id=image_category["group_id"],
        image_name=image_category["image_name"],
    )


async def styles_resolver(campaigns: list):
    for campaign in campaigns:
        if campaign["campaign_type"] == CampaignType.CATEGORY:
            _resolve_campaign_category(campaign)
