from typing import Union
import logging
from pathlib import Path
import re


def read_namespace(path: str) -> Union[tuple[None, None], tuple[set[str], set[str]]]:
    """
    Reads the namespace project file specified by path and return functions
    for which we want to create wrappers and which we want to export.

    Function names should be one per line, optional 'noR:' at the beginning
    will indicate that we want to create a wrapper, but not export it;
    comments begin with '#'

    :param path: path to your namespace file
    :return:
    """
    try:
        # in theory we don't expect any non-ascii characters, but better safe than sorry
        with open(path, 'r', encoding='utf-8') as fin:
            names = fin.readlines()
    except IOError:
        message = 'Couldn\'t retrieve namespace file "{}", assuming all functions'
        logging.warning(message.format(Path(path).absolute()))
        return None, None
    names = map(lambda x: re.sub(r'#.*$', '', x).strip(),
                names)  # remove comments
    names = filter(None, names)  # remove empty lines
    export = set()
    wrapper = set()
    for name in names:
        if name.startswith('noR:'):
            wrapper.add(name[4:])
        else:
            wrapper.add(name)
            export.add(name)
    return export, wrapper