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


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

    commit = os.environ.get("VROBBLER_COMMIT")
    if not commit:
        # Try to import from _commit.py module first
        try:
            from vrobbler._commit import commit as _commit
        except ImportError:
            pass
        else:
            if _commit and _commit != "unknown":
                return {"app_version": app_version, "git_commit": _commit}

        # Try to read from commit file (written during deploy)
        commit_file = Path("/var/lib/vrobbler/commit.txt")
        if commit_file.exists():
            try:
                commit = commit_file.read_text().strip()
                if commit:
                    return {"app_version": app_version, "git_commit": commit}
            except OSError:
                pass

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

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