#  Copyright (C) 2024
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Mike Orlov <m.orlov@abm-jsc.ru>
import argparse
from typing import Iterable

DEFAULT_KEY_VALUE_SEPARATOR = '='
DEFAULT_KWARG_FLAG_NAME = '-v'


def parse_args_as_file_with_kwargs(
        args: Iterable[str] | None = None,  # None means sys.argv[1:]
        kwarg_flag_name: str | None = None,  # None or empty str means default
        key_value_separator: str | None = None,  # None or empty str means default
) -> tuple[str | None, dict[str, str]]:
    """
    Used to parse cmd args
    >>> parse_args_as_file_with_kwargs(args=['../some.ini', '-v', 'key=42', '-v', 'foo=bar'])
    ('../some.ini', {'key': '42', 'foo': 'bar'})
    >>> parse_args_as_file_with_kwargs(args=[])
    (None, {})
    """
    kwarg_flag_name = kwarg_flag_name or DEFAULT_KWARG_FLAG_NAME
    key_value_separator = key_value_separator or DEFAULT_KEY_VALUE_SEPARATOR
    parser = argparse.ArgumentParser()
    parser.add_argument('config_file_path', nargs='?', default=None)
    overload_arg = parser.add_argument(kwarg_flag_name, action='append')
    parsed = parser.parse_args(args)
    raw_overload = getattr(parsed, overload_arg.dest) or []
    return parsed.config_file_path, dict([val.split(key_value_separator) for val in raw_overload])
