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

from type_cast import DataclassProtocol, unflatten_dict, to_dataclass
from typing_extensions import deprecated

from .parse_args_as_file_with_kwargs import parse_args_as_file_with_kwargs
from .read_file_as_dict import read_file_as_dict
from .._utils import update_dict_recursive

DP = TypeVar('DP', bound=DataclassProtocol)
DEFAULT_KEY_DEPTH_SEPARATOR = '.'


@deprecated("Use parse_args_as_dataclass_or_exit instead")
def parse_args_as_dataclass(
        dataclass_type: type[DP],
        flag_name: str = '-v',
        args: Iterable[str] | None = None,
        key_value_separator: str | None = None,
        key_depth_separator: str | None = None,
) -> DP:
    key_depth_separator: str = key_depth_separator or DEFAULT_KEY_DEPTH_SEPARATOR
    filepath, flat_overload = parse_args_as_file_with_kwargs(
        args=args, kwarg_flag_name=flag_name, key_value_separator=key_value_separator)
    config_dict = read_file_as_dict(filepath) if filepath else {}
    update_dict_recursive(config_dict, unflatten_dict(flat_overload, separator=key_depth_separator))
    return to_dataclass(config_dict, dataclass_type)
