import os
import subprocess
from importlib.metadata import version as get_version
from pathlib import Path


_GIT_COMMIT = None


def version_info(request):
    global _GIT_COMMIT

    try:
        app_version = get_version("vrobbler")
    except Exception:
        app_version = "unknown"

    commit = os.environ.get("VROBBLER_COMMIT")
    if commit:
        return {"app_version": app_version, "git_commit": commit}

    if _GIT_COMMIT is not None:
        return {"app_version": app_version, "git_commit": _GIT_COMMIT}

    try:
        from vrobbler._commit import commit as _commit
    except ImportError:
        pass
    else:
        if _commit and _commit != "unknown":
            _GIT_COMMIT = _commit
            return {"app_version": app_version, "git_commit": _GIT_COMMIT}

    commit_file = Path("/var/lib/vrobbler/commit.txt")
    if commit_file.exists():
        try:
            commit = commit_file.read_text().strip()
            if commit:
                _GIT_COMMIT = commit
                return {"app_version": app_version, "git_commit": _GIT_COMMIT}
        except OSError:
            pass

    PROJECT_ROOT = Path(__file__).resolve().parent.parent
    try:
        _GIT_COMMIT = (
            subprocess.check_output(
                ["git", "rev-parse", "--short", "HEAD"],
                cwd=PROJECT_ROOT,
                stderr=subprocess.DEVNULL,
            )
            .decode("utf-8")
            .strip()
        )
    except (subprocess.SubprocessError, FileNotFoundError):
        _GIT_COMMIT = "unknown"

    return {"app_version": app_version, "git_commit": _GIT_COMMIT}
