#  Copyright (C) 2021
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Mike Orlov <m.orlov@abm-jsc.ru>
#
import configparser
import logging
import os
import pathlib

from .read_file_text import read_file_text

logger = logging.getLogger(__file__)


class ParseError(Exception):
    pass


class IniParseError(ParseError):
    pass


def parse_ini_content(ini_content: str) -> dict[str, dict[str, str]]:
    config = configparser.RawConfigParser()
    try:
        config.read_string(ini_content)
    except configparser.Error as e:
        raise IniParseError(f"Failed to parse {ini_content=} as dict: {e=}") from None
    return {name: {key: config[name][key] for key in config[name]} for name in config.sections()}


def read_ini_file_by_path(
        path: str | pathlib.Path | os.PathLike, encoding: str | None = None
) -> dict[str, dict[str, str]]:
    logger.info(f"Attempt to read ini file by {path=}")
    return parse_ini_content(read_file_text(path=path, encoding=encoding))
