import os
import subprocess
from tempfile import TemporaryDirectory


def main() -> str:
    if subprocess.run(["cmake", "--version"]).returncode:
        raise RuntimeError("Could not find cmake")

    with TemporaryDirectory() as build_dir:
        # get the compiler id and version
        if subprocess.run(
            ["cmake", "-S", os.path.dirname(__file__), "-B", build_dir]
        ).returncode:
            raise RuntimeError(
                "Could not find a C++ 20 compiler. Do you have a C++ 20 compiler installed?"
            )

        # Get the compiler variables generated by the cmake file
        with open(os.path.join(build_dir, "compiler_id.txt")) as f:
            compiler_id_str = f.read().strip()
        with open(os.path.join(build_dir, "compiler_version.txt")) as f:
            compiler_version = f.read().strip().split(".", 1)[0]

    # convert the compiler id to an int so it can be used in a version number
    compiler_id_int = 0
    for b in compiler_id_str.encode("utf-8"):
        compiler_id_int <<= 8
        compiler_id_int += b

    # combine the compiler id and compiler version into a version number
    return f"==4.{compiler_id_int}.{compiler_version}"
