from typing import Optional

from maps_adv.adv_store.client import Client as AdvStoreClient
from maps_adv.billing_proxy.client import Client as BillingProxyClient
from maps_adv.warden.client.lib import TaskContext

from . import pipelines
from .normalizer import AppMetricOnlyNormalizerTask, MapkitAndAppMetricNormalizerTask
from .paid_till_processor import PaidTillProcessorTask

__all__ = ["events_processor", "events_normalizer", "paid_till_processor"]


async def events_normalizer(
    context: TaskContext,
    *,
    config: dict,
    ch_config: dict,
    **kwargs,
):
    task = AppMetricOnlyNormalizerTask(
        max_packet_size=config["MAX_PACKET_SIZE"],
        min_packet_size=config["MIN_PACKET_SIZE"],
        lag=config["LAG_PACKET_SIZE"],
        ch_client_params=ch_config,
        ch_query_id=config["CH_NORMALIZER_QUERY_ID"],
    )
    await task(context.client)


async def events_normalizer_mapkit(
    context: TaskContext,
    *,
    config: dict,
    ch_config: dict,
    **kwargs,
):
    task = MapkitAndAppMetricNormalizerTask(
        max_packet_size=config["MAX_PACKET_SIZE"],
        min_packet_size=config["MIN_PACKET_SIZE"],
        lag=config["LAG_PACKET_SIZE"],
        deduplication_window=config["DEDUPLICATION_WINDOW"],
        ch_client_params=ch_config,
        app_filter=config["MAPKIT_SOURCE_APP_FILTER"],
        recognised_apps=config["MAPKIT_RECOGNISED_APPS"],
        normalized_events_table_name=config["MAPKIT_NORMALIZER_TABLE_NAME"],
        ch_query_id=config["CH_NORMALIZER_QUERY_ID"],
    )
    await task(context.client)


async def events_processor(
    context: TaskContext,
    *,
    config: dict,
    ch_config: dict,
    adv_store_client: AdvStoreClient,
    billing_proxy_client: BillingProxyClient,
    build_revision: Optional[int] = None,
    **kwargs,
):
    task = pipelines.create_charger(
        adv_store_client=adv_store_client,
        billing_proxy_client=billing_proxy_client,
        lag_packet_size=config["LAG_PACKET_SIZE"],
        min_packet_size=config["MIN_PACKET_SIZE"],
        max_packet_size=config["MAX_PACKET_SIZE"],
        time_threshold_free_events=config["TIME_THRESHOLD_FREE_EVENTS"],
        ch_config=ch_config,
        campaigns_for_processing=config[
            "MONKEY_PATCH_CAMPAIGNS_FOR_BEEKEEPER"
        ],  # GEOPROD-4108
        build_revision=build_revision,
        ch_max_memory_usage=config["CH_MAX_MEMORY_USAGE"],
        ch_query_id=config["CH_PROCESSOR_QUERY_ID"],
    )
    await task(context)


async def paid_till_processor(
    context: TaskContext,
    *,
    config: dict,
    adv_store_client: AdvStoreClient,
    billing_proxy_client: BillingProxyClient,
    **kwargs,
):
    if config["EXPERIMENTAL_CHARGE_FIX_CAMPAIGNS"]:
        task = PaidTillProcessorTask(adv_store_client, billing_proxy_client)
        await task(context)
