"""
Setup the geowatch package mirror
"""


def main():
    import networkx as nx
    import ubelt as ub

    new_name = 'geowatch'
    old_name = 'watch'

    # new_name = 'NEW_MODULE'
    # old_name = 'OLD_MODULE'
    module = ub.import_module_from_name(old_name)

    module_dpath = ub.Path(module.__file__).parent
    repo_dpath = module_dpath.parent

    g = nx.DiGraph()
    g.add_node(module_dpath, label=module_dpath.name, type='dir')

    for root, dnames, fnames in module_dpath.walk():
        # dnames[:] = [d for d in dnames if not dname_block_pattern.match(d)]
        if '__init__.py' not in fnames:
            dnames.clear()
            continue

        g.add_node(root, label=root.name, type='dir')
        if root != module_dpath:
            g.add_edge(root.parent, root)

        # for d in dnames:
        #     dpath = root / d
        #     g.add_node(dpath, label=dpath.name)
        #     g.add_edge(root, dpath)

        for f in fnames:
            if f.endswith('.py'):
                fpath = root / f
                g.add_node(fpath, label=fpath.name, type='file')
                g.add_edge(root, fpath)

    for p in list(g.nodes):
        node_data = g.nodes[p]
        ntype = node_data.get('type', None)
        if ntype == 'dir':
            node_data['label'] = ub.color_text(node_data['label'], 'blue')
        elif ntype == 'file':
            node_data['label'] = ub.color_text(node_data['label'], 'green')

    nx.write_network_text(g)

    for node, node_data in g.nodes(data=True):
        if node_data['type'] == 'file':
            relpath = node.relative_to(module_dpath)
            new_fpath = repo_dpath / new_name / relpath
            new_fpath.parent.ensuredir()
            modname = ub.modpath_to_modname(node)
            if new_fpath.name == '__main__.py':
                new_fpath.write_text(ub.codeblock(
                    f'''
                    from {modname} import main
                    if __name__ == '__main__':
                        main()
                    '''))
            else:
                new_fpath.write_text(ub.codeblock(
                    f'''
                    # Autogenerated via:
                    # python ~/code/watch/dev/maintain/mirror_package_geowatch.py
                    def __getattr__(key):
                        import {modname} as mirror
                        return getattr(mirror, key)
                    '''))


if __name__ == '__main__':
    """
    CommandLine:
        python ~/code/watch/dev/maintain/mirror_package_geowatch.py

    python -c "import geowatch; print('geowatch.__version__ = ' + str(geowatch.__version__))"
    python -c "import geowatch; print('geowatch.__name__ = ' + str(geowatch.__name__))"

    python -m geowatch
    """
    main()
