from typing import Optional

__version__ = "N/A"
__release_commit__ = "$Format:%H$"
__full_version__: str = ""

IS_RELEASE_BUILD = False

if __release_commit__[1:-1] == "Format:%H":
    import subprocess

    try:
        devnull: Optional[int] = subprocess.DEVNULL
    except AttributeError:
        devnull = None  # Not supported, but not critical

    try:
        __version__ = (
            subprocess.check_output(
                ["git", "describe", "--tags"],
                stderr=devnull,
            )
            .strip()
            .decode("utf-8")
        )
        __release_commit__ = (
            subprocess.check_output(["git", "log", "--pretty=format:%H", "-n", "1"])
            .strip()
            .decode("utf-8")
        )
    except (subprocess.CalledProcessError, FileNotFoundError):
        __release_commit__ = "N/A"
        try:
            __version__ = (
                subprocess.check_output(
                    ["dpkg-parsechangelog", "-SVersion"],
                    stderr=devnull,
                )
                .strip()
                .decode("utf-8")
            )

        except (subprocess.CalledProcessError, FileNotFoundError):
            __version__ = "N/A"
else:
    # Disregard snapshot versions (gbp dch -S) as "release builds"
    IS_RELEASE_BUILD = ".gbp" not in __version__

if __version__.startswith("debian/"):
    __version__ = __version__[7:]

if __release_commit__ != "N/A":
    __full_version__ = "%s (commit: %s)" % (__version__, __release_commit__)
else:
    __full_version__ = __version__
