#!/usr/bin/env python3

import pathlib
import collections
import re

ROOT = pathlib.Path(__file__).parent.parent
HEADER = "# Generated by scripts/relative_imports.py, do not edit below this line."

GENERATED_MODULES : str = """
renpy.styledata.style_activate_functions
renpy.styledata.style_functions
renpy.styledata.style_hover_functions
renpy.styledata.style_idle_functions
renpy.styledata.style_insensitive_functions
renpy.styledata.style_selected_activate_functions
renpy.styledata.style_selected_functions
renpy.styledata.style_selected_hover_functions
renpy.styledata.style_selected_idle_functions
renpy.styledata.style_selected_insensitive_functions
"""

def find_modules():
    """
    Finds the names of all modules.
    """

    modules : list[str] = GENERATED_MODULES.split()

    # A list of root, pattern pairs.
    patterns = [
        (ROOT, "renpy/**/*.py"),
        (ROOT, "renpy/**/*.pyx"),
    ]

    for root, pattern in patterns:
        for i in ROOT.glob(pattern):
            i = i.relative_to(ROOT)
            mod = str(i.with_suffix("")).replace("/", ".")
            if mod.endswith(".__init__"):
                mod = mod[:-9]

            modules.append(mod)

    modules.sort()

    package_modules = collections.defaultdict(list)

    for mod in modules:
        package, _, module = mod.rpartition(".")

        if not package.startswith("renpy"):
            continue

        package_modules[package].append(module)

    return package_modules

def generate(package, modules):

    if package == "renpy.common":
        return

    fn = package.replace(".", "/") + "/__init__.py"
    p = ROOT / fn

    text = p.read_text()

    text = text.split("\n")
    new_text = [ ]

    for i in text:
        if i == HEADER:
            break

        new_text.append(i)

    text = "\n".join(new_text)

    text = text.rstrip("\n")
    text = text + "\n\n\n"

    text += HEADER + "\n"
    text += "import typing\n"
    text += "\n"
    text += "if typing.TYPE_CHECKING:\n"

    for mod in modules:
        text += f"    from . import {mod} as {mod}\n"

    p.write_text(text)

def main():
    package_modules = find_modules()
    for package, modules in package_modules.items():
        generate(package, modules)


if __name__ == "__main__":
    main()
