from typing import List, Optional

from .base import BaseCoefCpmFilter, CpmUndefined, CpmCoef
from maps_adv.billing_proxy.lib.domain.enums import CreativeType, CpmCoefFieldType


class CreativePresenceCpmFilter(BaseCoefCpmFilter):
    def __init__(self, *, creative_groups: List[dict], **kwargs):
        super().__init__(**kwargs)
        self._creative_type_to_rate = {
            group["type"]: group["rate"] for group in creative_groups
        }

    def get_coefs(
        self, *, creative_types: Optional[List[CreativeType]], **kwargs
    ) -> list[CpmCoef]:
        rates = (
            [
                (creative_type, self._creative_type_to_rate[creative_type])
                for creative_type in creative_types
                if creative_type in self._creative_type_to_rate
            ]
            if creative_types
            else []
        )
        if rates:
            max_rate = max(rates, key=lambda rate: rate[1])
            return [
                CpmCoef(
                    CpmCoefFieldType.CREATIVE,
                    max_rate[0],
                    max_rate[1],
                )
            ]

        if "default_rate" in self.settings:
            return [
                CpmCoef(CpmCoefFieldType.CREATIVE, None, self.settings["default_rate"])
            ]

        raise CpmUndefined(
            f"Unsupported creatives: {[creative_type.value for creative_type in creative_types]}"
        )


cpm_filters = {
    "creative_presence_audio_banner": CreativePresenceCpmFilter(
        default_rate=1,
        creative_groups=[{"type": CreativeType.AUDIO_BANNER, "rate": 1.25}],
    )
}
