# Copyright NTESS. See COPYRIGHT file for details.
#
# SPDX-License-Identifier: MIT

import os
import subprocess
from typing import TextIO


def version_components_from_git(full: bool = False) -> tuple[int, int, int, str]:
    dir = os.getenv("PROJECT_SOURCE_DIR") or os.path.dirname(__file__)
    while True:
        if os.path.exists(os.path.join(dir, ".git")):
            break
        dir = os.path.dirname(dir)
        if dir == os.path.sep:
            raise GitRepoNotFoundError(os.path.dirname(__file__))
    out = subprocess.check_output(
        ["git", "-C", dir, "log", "-1", "--pretty=format:%ad %h", "--date=short"],
        encoding="utf-8",
    )
    parts = out.split()
    date, local = parts[:2]
    major, minor, micro = [int(_) for _ in date.split("-")]
    if full:
        proc = subprocess.Popen(["git", "-C", dir, "diff", "--quiet"])
        proc.wait()
        if proc.returncode:
            local += "-dirty"
    return major - 2000, minor, micro, local


class GitRepoNotFoundError(Exception):
    pass


def write_version_file(file: TextIO, major: int, minor: int, micro: int, local: str) -> None:
    file.write(
        f"""# Version file automatically generated by hpc_connect

__static_version_tuple__: tuple[int, int, int, str] = ({major}, {minor}, {micro}, {local!r})
__static_version__: str = "{major}.{minor}.{micro}+{local}"

def __getattr__(name):

    from hpc_connect.util.dynamic_version import version_components_from_git
    from hpc_connect.util.dynamic_version import GitRepoNotFoundError

    if name not in ("version", "__version__", "version_info", "__version_info__"):
        raise AttributeError(name)
    try:
        major, minor, micro, local = version_components_from_git(full=True)
        if name in ("version", "__version__"):
            return f"{{major}}.{{minor}}.{{micro}}+{{local}}"
        else:
            return (major, minor, micro, local)
    except GitRepoNotFoundError:
        if name in ("version", "__version__"):
            return __static_version__
        else:
            return __static_version_tuple__
"""
    )


def __generate_dynamic_version__():
    major, minor, micro, local = version_components_from_git()
    with open(os.path.join(os.path.dirname(__file__), "../version.py"), "w") as fh:
        write_version_file(fh, major, minor, micro, local)
    if "INCLUDE_LOCAL_VERSION" in os.environ:
        return f"{major}.{minor}.{micro}+{local}"
    return f"{major}.{minor}.{micro}"
