import asyncio
import logging

import click
from csirtmu.core.logging import setup_logging
from csirtmu.core.temporal import print_all_schedules
from csirtmu.core.temporal.config import create_temporal_client
from csirtmu.core.temporal.create_worker import start_temporal_worker

from csirtmu.perun_sync import workers
from csirtmu.perun_sync.config import AppConfig


@click.group()
def cli() -> None:
    pass


@cli.command()
@click.argument("worker_name", type=click.Choice(list(workers.keys())))
def start_worker(worker_name: str) -> None:
    """
    Start a temporal worker by name.
    """
    _setup_logging()
    asyncio.run(start_temporal_worker(worker_name, workers))  # type: ignore


async def _list_schedules() -> None:
    tc = await create_temporal_client(AppConfig.get().temporal)
    await print_all_schedules(tc)


@cli.command()
def list_schedules() -> None:
    """
    Print all registered schedules on the temporal server to stdout.
    """
    setup_logging(
        pretty_print_exception=False,
        level_const=logging.INFO,
        verbose_origin=False,
        formatter_const="colored",
    )
    asyncio.run(_list_schedules())


def _setup_logging() -> None:
    config = AppConfig.get()
    setup_logging(
        pretty_print_exception=config.logging.level_const == logging.DEBUG and config.logging.pretty_print_exceptions,
        level_const=config.logging.level_const,
        verbose_origin=config.logging.verbose_origin,
        formatter_const=config.logging.formatter_const,
    )


if __name__ == "__main__":
    cli()
