import os
import sys
import asyncio
from logging.config import dictConfig
from typing import cast

import click
from arq.worker import create_worker
from pydantic.utils import import_string

from intranet.trip.sftp.src.config import settings
from intranet.trip.sftp.src.error_booster import init_error_booster
from intranet.trip.sftp.src.logging import LOGGING_CONFIG
from intranet.trip.sftp.src.redis import create_redis_pool


@click.command('arq')
@click.argument('worker-settings', type=str, required=True)
def cli(*, worker_settings: str) -> None:
    if settings.ENABLE_ERROR_BOOSTER:
        init_error_booster()
    sys.path.append(os.getcwd())
    worker_settings_ = cast('WorkerSettingsType', import_string(worker_settings))
    dictConfig(LOGGING_CONFIG)

    loop = asyncio.get_event_loop()
    pool = loop.run_until_complete(create_redis_pool())
    worker = create_worker(worker_settings_, redis_pool=pool)
    worker.run()
