#!/usr/bin/env bash
# scripts/build-image — build a precis docker image with baked-in
# git + build metadata.
#
# The metadata (git sha, dirty flag, describe, branch, build time, host,
# user) lands on the image as env vars and is surfaced at runtime by
# `get(kind='skill', id='precis-status')` so an agent can answer "what
# version am I, what DB am I connected to" without grovelling through
# compose files.
#
# Usage:
#   scripts/build-image                # builds the `precis` service
#   scripts/build-image precis-dev     # builds the dev image
#
# The compose file lives in this repo at
# docker/dev/compose.yaml (override with $PRECIS_COMPOSE).
# This wrapper collects the values on the host and threads them in via
# --build-arg so you don't have to edit the compose file by hand.
set -euo pipefail

cd "$(dirname "$0")/.."

INFRA_COMPOSE="${PRECIS_COMPOSE:-${PWD}/docker/dev/compose.yaml}"
if [[ ! -f "${INFRA_COMPOSE}" ]]; then
    echo "ERR: compose file not found at ${INFRA_COMPOSE}" >&2
    echo "     set PRECIS_COMPOSE=/path/to/compose.yaml to override" >&2
    exit 1
fi

SERVICE="${1:-precis}"

# The compose build's models stage COPYs from the `premodels` context
# (additional_contexts in compose.yaml) — ensure the tag exists first:
# seed-bootstrap from any model-bearing local image, else build the models
# stage once. Mirrors scripts/precis-shell's guard; without it a fresh
# machine gets a confusing docker-image:// resolve error.
BASE_IMAGE="precis-mcp:premodels"
have_image() { docker image inspect "$1" >/dev/null 2>&1; }
if ! have_image "${BASE_IMAGE}"; then
    for seed in precis-mcp:latest precis-mcp:dev precis-dev; do
        if have_image "${seed}"; then
            echo "[build-image] tagging ${seed} as ${BASE_IMAGE} (seed bootstrap)" >&2
            docker tag "${seed}" "${BASE_IMAGE}"
            break
        fi
    done
fi
if ! have_image "${BASE_IMAGE}"; then
    echo "[build-image] building ${BASE_IMAGE} (target=models — slow, one-time)" >&2
    docker build \
        --target models \
        --build-arg "UID=$(id -u)" \
        --build-arg "GID=$(id -g)" \
        -t "${BASE_IMAGE}" \
        -f docker/Dockerfile \
        .
fi

GIT_SHA="$(git rev-parse HEAD)"
GIT_SHA_SHORT="$(git rev-parse --short=12 HEAD)"
if [[ -z "$(git status --porcelain)" ]]; then
    GIT_DIRTY=0
else
    GIT_DIRTY=1
fi
GIT_DESCRIBE="$(git describe --tags --always --dirty --long 2>/dev/null || echo unknown)"
# Latest annotated/lightweight tag reachable from HEAD — what an
# operator means by "what release is this?" (e.g. v8.4.4).
GIT_LAST_TAG="$(git describe --tags --abbrev=0 2>/dev/null || echo unknown)"
GIT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
BUILD_TIME="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
BUILD_HOST="$(hostname -f 2>/dev/null || hostname)"
BUILD_USER="${USER:-unknown}"

# Resolve autocatpath's current main HEAD on the host so the dev image's autocatpath
# layer busts (and re-fetches) exactly when autocatpath main advances — Docker keys
# that layer on command text, so a bare `@main` would silently stay stale. See
# the AUTOCATPATH_REV ARG in docker/Dockerfile. Falls back to the `main` ref when
# the host is offline (uv still resolves it, just without the cache-bust).
AUTOCATPATH_REV="$(git ls-remote https://github.com/retospect/catpath main 2>/dev/null | cut -f1)"
AUTOCATPATH_REV="${AUTOCATPATH_REV:-main}"

# The catpath repo is private: the in-build `git fetch` needs a token the
# host's keychain can't supply. Threaded as a BuildKit secret (see the
# autocatpath layer in docker/Dockerfile) — an empty value is harmless when
# anonymous access works. A caller-set GH_TOKEN wins over `gh auth token`.
export GH_TOKEN="${GH_TOKEN:-$(gh auth token 2>/dev/null || true)}"

exec docker compose -f "${INFRA_COMPOSE}" build \
    --build-arg "AUTOCATPATH_REV=${AUTOCATPATH_REV}" \
    --build-arg "PRECIS_GIT_LAST_TAG=${GIT_LAST_TAG}" \
    --build-arg "PRECIS_GIT_SHA=${GIT_SHA}" \
    --build-arg "PRECIS_GIT_SHA_SHORT=${GIT_SHA_SHORT}" \
    --build-arg "PRECIS_GIT_DIRTY=${GIT_DIRTY}" \
    --build-arg "PRECIS_GIT_DESCRIBE=${GIT_DESCRIBE}" \
    --build-arg "PRECIS_GIT_BRANCH=${GIT_BRANCH}" \
    --build-arg "PRECIS_BUILD_TIME=${BUILD_TIME}" \
    --build-arg "PRECIS_BUILD_HOST=${BUILD_HOST}" \
    --build-arg "PRECIS_BUILD_USER=${BUILD_USER}" \
    "${SERVICE}"
