from __future__ import annotations

from pathlib import Path

from stdlibs import stdlib_module_names

PATH = Path("crates") / "ruff_python_stdlib" / "src" / "sys" / "known_stdlib.rs"
VERSIONS: list[tuple[int, int]] = [
    (3, 7),
    (3, 8),
    (3, 9),
    (3, 10),
    (3, 11),
    (3, 12),
    (3, 13),
]

with PATH.open("w") as f:
    f.write(
        """\
//! This file is generated by `scripts/generate_known_standard_library.py`

pub fn is_known_standard_library(minor_version: u8, module: &str) -> bool {
    matches!((minor_version, module),
""",
    )

    modules_by_version = {}

    for major_version, minor_version in VERSIONS:
        modules = set()

        for module in stdlib_module_names(f"{major_version}.{minor_version}"):
            if module != "__future__":
                modules.add(module)

        modules_by_version[minor_version] = modules

    # First, add a case for the modules that are in all versions.
    ubiquitous_modules = set.intersection(*modules_by_version.values())

    f.write("(_, ")
    for i, module in enumerate(sorted(ubiquitous_modules)):
        if i > 0:
            f.write(" | ")
        f.write(f'"{module}"')
    f.write(")")
    f.write("\n")

    # Next, add any version-specific modules.
    for _major_version, minor_version in VERSIONS:
        version_modules = set.difference(
            modules_by_version[minor_version],
            ubiquitous_modules,
        )

        f.write(" | ")
        f.write(f"({minor_version}, ")
        for i, module in enumerate(sorted(version_modules)):
            if i > 0:
                f.write(" | ")
            f.write(f'"{module}"')
        f.write(")")
        f.write("\n")

    f.write(
        """\
        )
}
    """,
    )
