from typing import TextIO
from typing import Tuple
from typing import Mapping
import toml


def parse_pyproject_toml(file: TextIO) -> Tuple[Mapping, Mapping]:
    """ Parse a pyproject.toml file

     This function assumes that the pyproject.toml contains a poetry and
     poetry2conda config sections.

    Parameters
    ----------
    file
        A file-like object containing a pyproject.toml file.

    Returns
    -------
    A tuple with the poetry2conda and poetry config.

    Raises
    ------
    RuntimeError
        When an expected configuration section is missing.


    """
    pyproject_toml = toml.loads(file.read())
    poetry_config = pyproject_toml.get("tool", {}).get("poetry", {})
    if not poetry_config:
        raise RuntimeError(f"tool.poetry section was not found on {file.name}")

    poetry2conda_config = pyproject_toml.get("tool", {}).get("poetry2conda", {})
    if not poetry2conda_config:
        raise RuntimeError(f"tool.poetry2conda section was not found on {file.name}")

    if "name" not in poetry2conda_config or not isinstance(
        poetry2conda_config["name"], str
    ):
        raise RuntimeError(f"tool.poetry2conda.name entry was not found on {file.name}")

    return poetry2conda_config, poetry_config