# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Debusine worker launcher."""

import argparse
import asyncio
import logging
import sys
from collections.abc import Sequence

from debusine.utils import debusine_version
from debusine.worker import Worker
from debusine.worker.config import ConfigHandler


def main(argv: Sequence[str]) -> None:
    """Run the debusine-worker command (main entry-point)."""
    config_paths = ', '.join(ConfigHandler.default_directories)
    parser = argparse.ArgumentParser(
        prog='debusine-worker',
        description=f'Start Debusine worker process: register if needed and '
        f'connects to the server. The configuration is searched in '
        f'the files config.ini and token in the '
        f'directories {config_paths})',
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {debusine_version() or 'uninstalled-version'}",
    )
    parser.add_argument(
        '--log-level',
        help='Minimum log level. Overrides log-level (in [General] section) '
        'from config.ini. If not specified anywhere logs '
        f'{logging.getLevelName(Worker.DEFAULT_LOG_LEVEL)} and above.',
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
    )
    parser.add_argument(
        '--working-directory',
        type=str,
        help='Execute tasks within this directory. Overrides working-directory '
        '(in [General] section) from config.ini. If not specified anywhere '
        'executes tasks in $HOME/workdir.',
    )

    args = parser.parse_args(argv)

    async def async_main() -> None:
        async with Worker(
            log_level=args.log_level,
            working_directory=args.working_directory,
        ) as worker:
            await worker.main()

    asyncio.run(async_main())


def entry_point() -> None:  # pragma: no cover
    """Entry point for the packaging."""
    main(sys.argv[1:])


if __name__ == '__main__':
    entry_point()
