import logging

from datetime import datetime, timezone
from operator import itemgetter

from maps_adv.billing_proxy.client import Client
from maps_adv.export.lib.pipeline.exceptions import StepException

logger = logging.getLogger(__name__)


class ApplyOrderDiscountsStep:
    def __init__(self, config):
        self._client = Client(config.BILLING_URL)

    async def __call__(self, campaigns):
        campaigns = list(filter(lambda c: c.get("order_id"), campaigns))
        try:
            async with self._client as billing_client:
                order_discounts = await billing_client.fetch_orders_discounts(
                    datetime.now(timezone.utc),
                    *set(map(itemgetter("order_id"), campaigns))
                )
        except Exception:
            logger.exception("Failed to fetch order discounts")
            raise StepException()

        for campaign in campaigns:
            coef = order_discounts.get(campaign["order_id"])
            display_limit = campaign.get("total_daily_display_limit")
            if coef and display_limit:
                campaign["total_daily_display_limit"] = int(display_limit / coef)
            action_limit = campaign.get("total_daily_action_limit")
            if coef and action_limit:
                campaign["total_daily_action_limit"] = int(action_limit / coef)
