from typing import TYPE_CHECKING

from csirtmu.core.temporal import TemporalClient
from redis import Redis

from csirtmu.beta.config import QueueConfig
from csirtmu.beta.handler import Handler
from csirtmu.beta.queue_builder import QueueBuilder
from csirtmu.beta.rt_queue import Queue

if TYPE_CHECKING:
    from redis import Redis


class HandlerBuilder:
    def __init__(self, client: TemporalClient, redis: "Redis[bytes]") -> None:
        self.queue_map: dict[str, Queue] = {}
        self.tc = client
        self.redis = redis

    def build(self, queue_mapping: list[QueueConfig]) -> Handler:
        for queue in queue_mapping:
            self.queue_map[queue.name] = self.build_queue(queue)
        return self.to_handler()

    def to_handler(self) -> Handler:
        return Handler(self.queue_map, self.tc, self.redis)

    def build_queue(self, queue_config: QueueConfig) -> Queue:
        builder = QueueBuilder(queue_config.name, temporal_queue=queue_config.temporal_queue)
        for workflow in queue_config.workflows:
            for transaction_type in workflow.get_transaction_types:
                builder.add_rule(transaction_type, workflow.get_workflow_name, workflow.params)
        return builder.to_queue()
