import os
from pathlib import Path

_VERSION = None


def app_version(request):
    global _VERSION
    if _VERSION is None:
        # 1. Environment variable (set in Docker/deployment)
        _VERSION = os.environ.get("APP_VERSION", "").strip()
        if not _VERSION:
            # 2. Try VERSION file at common locations
            base = Path(__file__).resolve().parent.parent  # app/
            for candidate in [
                base.parent / "VERSION",  # repo root (local dev)
                base / "VERSION",          # app/ dir (Docker)
            ]:
                try:
                    _VERSION = candidate.read_text().strip()
                    break
                except FileNotFoundError:
                    continue
            else:
                _VERSION = "unknown"
    return {"APP_VERSION": _VERSION}
