from typing import Optional, List

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


class RubricNameCpmFilter(BaseCoefCpmFilter):
    def __init__(self, *, rubric_groups: dict, **kwargs):
        super().__init__(**kwargs)
        self._rubric_group_to_rate = {
            group["name"]: group["rate"] for group in rubric_groups
        }

    def get_coefs(
        self, *, rubric_name: Optional[RubricName], **kwargs
    ) -> List[CpmCoef]:
        if rubric_name and rubric_name in self._rubric_group_to_rate:
            return [
                CpmCoef(
                    CpmCoefFieldType.RUBRIC,
                    rubric_name,
                    self._rubric_group_to_rate[rubric_name],
                )
            ]

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

        raise CpmUndefined(f"Unknown rubric: {rubric_name}")


cpm_filters = {
    "rubric_name_common": RubricNameCpmFilter(
        default_rate=1,
        rubric_groups=[
            {
                # Realty.
                "rate": 3,
                "name": RubricName.REALTY,
            },
            {
                # Auto.
                "rate": 2,
                "name": RubricName.AUTO,
            },
        ],
    ),
    "rubric_name_common_v2": RubricNameCpmFilter(
        default_rate=1,
        rubric_groups=[
            {
                # Realty.
                "rate": 3,
                "name": RubricName.REALTY,
            }
        ],
    ),
}
