"""
Statically ports utilities from ubelt needed by xdoctest.

Similar Scripts:
    ~/code/xdoctest/dev/maintain/port_ubelt_utils.py
    ~/code/mkinit/dev/maintain/port_ubelt_code.py
    ~/code/line_profiler/dev/maintain/port_utilities.py
"""


def _autogen_xdoctest_utils():
    import ubelt as ub
    import liberator
    lib = liberator.Liberator()

    from ubelt import util_import
    lib.add_dynamic(util_import.split_modpath)
    lib.add_dynamic(util_import.modpath_to_modname)
    lib.add_dynamic(util_import.modname_to_modpath)
    lib.add_dynamic(util_import.import_module_from_name)
    lib.add_dynamic(util_import.import_module_from_path)
    lib.add_dynamic(util_import._pkgutil_modname_to_modpath)
    lib.add_dynamic(util_import._importlib_import_modpath)
    lib.add_dynamic(util_import.is_modname_importable)

    lib.expand(['ubelt'])
    text = lib.current_sourcecode()
    print(text)

    """
    pip install rope
    pip install parso
    """

    # target_fpath = ub.Path('~/code/xdoctest/src/xdoctest/utils/util_import.py').expand()
    import parso
    import xdoctest
    target_fpath = ub.Path(xdoctest.utils.util_import.__file__)

    new_module = parso.parse(text)
    old_module = parso.parse(target_fpath.read_text())
    new_names = [child.name.value for child in new_module.children if child.type in {'funcdef', 'classdef'}]
    old_names = [child.name.value for child in old_module.children if child.type in {'funcdef', 'classdef'}]

    print(set(old_names) - set(new_names))
    print(set(new_names) - set(old_names))

    prefix = ub.codeblock(
        '''
        """
        This file was autogenerated based on code in ubelt via
        dev/port_ubelt_utils.py in the xdoctest repo
        """
        ''')

    # Remove doctest references to ubelt
    new_lines = []
    import re
    for line in text.split('\n'):
        if line.strip().startswith('>>> from ubelt'):
            continue
        if line.strip().startswith('>>> import ubelt as ub'):
            line = re.sub('>>> .*', '>>> # xdoctest: +SKIP("ubelt dependency")', line)
        new_lines.append(line)

    text = '\n'.join(new_lines)
    target_fpath.write_text(prefix + '\n' + text + '\n')


if __name__ == '__main__':
    """
    CommandLine:
        python ~/code/xdoctest/dev/maintain/port_ubelt_utils.py
    """
    _autogen_xdoctest_utils()
