"""/version endpoint — resolves the deployed commit hash by trying
several sources in order. Borrowed from remarkbox: deploy-time file
first, then the legacy setup.py-baked file, then a runtime
`git rev-parse` for dev, then "unknown".

The CI build writes commit-hash.txt to the artifact tarball
(.gitlab-ci.yml:42 `echo $CI_COMMIT_SHA >> commit-hash.txt`); salt
deploys it to /opt/make_post_sell/. setup.py also rewrites the
in-package GIT_HASH file at install time — that still works as a
fallback for any environment we haven't migrated to commit-hash.txt
yet.
"""

import os
import subprocess

from pyramid.view import view_config

VERSION = "1.1.5"


_this_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def _resolve_git_hash():
    # 1. Deploy-time commit-hash.txt (preferred). Salt extracts the
    # CI artifact to /opt/make_post_sell/; check a few neighbour paths.
    for candidate in (
        "/opt/make_post_sell/commit-hash.txt",
        "/opt/make_post_sell/env/commit-hash.txt",
        os.path.join(_this_dir, "..", "commit-hash.txt"),
    ):
        try:
            with open(candidate) as f:
                sha = f.read().strip()
                if sha:
                    return sha[:7]
        except OSError:
            continue

    # 2. Legacy in-package GIT_HASH (setup.py rewrites it on install).
    legacy = os.path.join(_this_dir, "GIT_HASH")
    try:
        with open(legacy) as f:
            sha = f.read().strip()
            if sha:
                return sha[:7]
    except OSError:
        pass

    # 3. Dev environment: ask git directly.
    try:
        return subprocess.check_output(
            ["git", "rev-parse", "--short", "HEAD"],
            cwd=_this_dir,
            stderr=subprocess.DEVNULL,
        ).decode().strip()
    except Exception:
        return "unknown"


GIT_HASH = _resolve_git_hash()


@view_config(route_name="version", renderer="json")
def version(request):
    return {"version": VERSION, "hash": GIT_HASH}
