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

from .ini_reader import read_ini_file_by_path
from .dataclass_protocol import DataclassProtocol
from .dict_to_dataclass import dict_to_dataclass
from .toml_reader import read_toml_file_by_path
from .update_dict_recursive import update_dict_recursive
from .unflatten_dict import unflatten_dict

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


def parse_args_as_dataclass(dataclass_type: type[DP], flag_name: str = '-v', args: Iterable[str] | None = None) -> DP:
    parser = argparse.ArgumentParser()
    parser.add_argument('config_file_path', nargs='?', default=None)
    overload_arg = parser.add_argument(flag_name, action='append')
    parsed = parser.parse_args(args)
    config = read_config(parsed.config_file_path) if parsed.config_file_path else {}
    raw_overload = getattr(parsed, overload_arg.dest) or []
    overload: dict[str, str | dict[str, str | dict]] = unflatten_dict(dict([val.split('=') for val in raw_overload]))
    update_dict_recursive(config, overload)
    return dict_to_dataclass(config, dataclass_type)


def read_config(config_file_path: str) -> dict:
    extension = config_file_path.rsplit('.', 1)[-1]
    if extension == 'toml':
        return read_toml_file_by_path(config_file_path)
    if extension == 'ini':
        return read_ini_file_by_path(config_file_path)
    raise TypeError(f'Unknown {extension=}')
