import asyncio
import logging

import click
from csirtmu.core.temporal.create_worker import create_temporal_worker

from csirtmu.beta_temporal.config import AppConfig
from csirtmu.beta_temporal.workflows import HandleTransaction, PeriodicWorkflows, RetryFailedTransactions, TaskWorkflows


@click.command()
@click.argument("worker", type=click.Choice(["handle-transactions", "process-workflows", "periodic-workflows"]))
def cli(worker: str) -> None:
    match worker:
        case "handle-transactions":
            asyncio.run(handle_transactions())
        case "process-workflows":
            asyncio.run(process_workflows())
        case "periodic-workflows":
            asyncio.run(process_periodic_workflows())
        case _:
            pass


async def handle_transactions() -> None:
    config = AppConfig.get()
    worker = await create_temporal_worker([HandleTransaction], config)
    await worker.run()


async def process_workflows() -> None:
    config = AppConfig.get()
    worker = await create_temporal_worker(TaskWorkflows, config, task_queue=config.temporal.beta_tasks_queue)

    # silence very noisy httpx logger
    logging.getLogger("httpx").setLevel("WARN")
    await worker.run()


async def process_periodic_workflows() -> None:
    config = AppConfig.get()

    if config.transaction_retention.store_failed_transactions:
        PeriodicWorkflows.append(RetryFailedTransactions)
    worker = await create_temporal_worker(PeriodicWorkflows, config, task_queue=config.temporal.periodic_tasks_queue)
    await worker.run()


if __name__ == "__main__":
    cli()
